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

前端 未结 12 1101
甜味超标
甜味超标 2020-12-04 15:54

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()->group         


        
12条回答
  •  情深已故
    2020-12-04 16:42

    I had a similar problem, and found a way to work around it.

    The problem is the way Laravel's query builder handles aggregates. It takes the first result returned and then returns the 'aggregate' value. This is usually fine, but when you combine count with groupBy you're returning a count per grouped item. So the first row's aggregate is just a count of the first group (so something low like 1 or 2 is likely).

    So Laravel's count is out, but I combined the Laravel query builder with some raw SQL to get an accurate count of my grouped results.

    For your example, I expect the following should work (and let you avoid the get):

    $query = $ad->getcodes()->groupby('pid')->distinct();
    $count = count(\DB::select($query->toSql(), $query->getBindings()));
    

    If you want to make sure you're not wasting time selecting all the columns, you can avoid that when building your query:

     $query = $ad->select(DB::raw(1))->getcodes()->groupby('pid')->distinct();
    

提交回复
热议问题