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

前端 未结 12 1137
甜味超标
甜味超标 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:36

    Anyone else come across this post, and not finding the other suggestions to work?

    Depending on the specific query, a different approach may be needed. In my case, I needed either count the results of a GROUP BY, e.g.

    SELECT COUNT(*) FROM (SELECT * FROM a GROUP BY b)
    

    or use COUNT(DISTINCT b):

    SELECT COUNT(DISTINCT b) FROM a
    

    After some puzzling around, I realised there was no built-in Laravel function for either of these. So the simplest solution was to use use DB::raw with the count method.

    $count = $builder->count(DB::raw('DISTINCT b'));
    

    Remember, don't use groupBy before calling count. You can apply groupBy later, if you need it for getting rows.

提交回复
热议问题