Laravel Eloquent - distinct() and count() not working properly together

Inigo EC picture Inigo EC · Feb 21, 2015 · Viewed 291.4k times · Source

So I'm trying to get the number of distinct pids on a query, but the returned value is wrong.

This is what I try to do:

$ad->getcodes()->groupby('pid')->distinct()->count()

what returns the value "2", while the value it should return, should be "1".

As a workaround, I'm doing this:

count($ad->getcodes()->groupby('pid')->distinct()->get())

what works fine and returns "1"

Is there any rule where count and distinct cannot be on the same query? I find the workaround kind of "heavy", I would like to make the original query work :(

Answer

Suresh Bala picture Suresh Bala · Apr 19, 2015

The following should work

$ad->getcodes()->distinct('pid')->count('pid');