Eager Loading withCount ignores Distinct #38792
Unanswered
kieranmetcalfe
asked this question in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
If I have, say, Posts [many] Comments [one] Users and I want to know how many users have commented on a post I can use:
This works as expected - returning the distinct users who have commented on the post.
But, if I wish to count that, and eager load it via withCount('users') it returns the full count of one user per comment.
It seems that this is because the subquery generated is:
... (select count(*) from users inner join comments on users.id = comments.user_id where posts.id = commments.post_id) as users_count ...
Whereas, i get the correct results if I change that to:
... (select count(distinct users.id) from users inner join comments on users.id = comments.user_id where posts.id = commments.post_id) as users_count ...
From digging into the code of Illuminate\Database\Eloquent\Concerns\QueriesRelationships, the withCount (510 - 519) function says:
public function withCount($relations) { return $this->withAggregate(is_array($relations) ? $relations : func_get_args(), '*', 'count'); }
The * is hard coded in the 2nd param for withAggregate. Is there a way to detect the value of the Query\Builder distinct flag and change that line to replace it with 'distinct users.id' (or the relevant foreign table name, obviously).
I'm not sure if this breaks anything else, or I'm missing the way to do this properly, but it feels like a bug in the way it's creating the subselect.
What do folk think?
Beta Was this translation helpful? Give feedback.
All reactions