Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Fix withCount() and withoutGlobalScopes() #25280

Merged
merged 1 commit into from
Aug 21, 2018
Merged

[5.6] Fix withCount() and withoutGlobalScopes() #25280

merged 1 commit into from
Aug 21, 2018

Conversation

staudenmeir
Copy link
Contributor

withoutGlobalScopes() doesn't work on withCount() relationships:

class Post extends Model {
    use SoftDeletes;
}

class User extends Model {
    public function allPosts() {
        return $this->hasMany(Post::class)->withoutGlobalScopes();
    }
}

User::withCount('allPosts')->get();
# expected
select "users".*,
  (select count(*)
   from "posts"
   where "users"."id" = "posts"."user_id")
  as "all_posts_count"
from "users"

# actual
select "users".*,
  (select count(*)
   from "posts"
   where "users"."id" = "posts"."user_id"
     and "posts"."deleted_at" is null) <--- The SoftDeletes scope should be missing.
  as "all_posts_count"
from "users"

This is caused by the way withCount() and mergeConstraintsFrom() merge the scopes.

We can fix it by explicitly adding all the scopes to $removedScopes (via withoutGlobalScope()).

@taylorotwell taylorotwell merged commit 9363e50 into laravel:5.6 Aug 21, 2018
@staudenmeir staudenmeir deleted the with-count-global-scopes branch August 21, 2018 14:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants