Eloquent count() always returns 1

前端 未结 2 400
别跟我提以往
别跟我提以往 2021-01-14 13:16

I have the following query:

Item::select([\'items.id\', \'inventory.quantity\'])
    ->leftJoin(\'inventory\', \'items.id\', \'=\', \'inventory.item_id\')         


        
相关标签:
2条回答
  • 2021-01-14 13:33

    If you only need the correct number of rows from a grouped result, and you don't care that much about the performance then you can call get() first and then call count() on that.

    $count = Item::select(['items.id', 'inventory.quantity'])
        ->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
        ->groupBy('items.id')
        ->get()
        ->count();
    
    0 讨论(0)
  • 2021-01-14 13:45

    Yes, count returns only 1 row, always.

    You would probably want:

    Item::select(['items.id as id', 'inventory.quantity as quantity'])
     ->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
     ->groupBy('items.id')
     ->lists('quantity', 'id');
    

    this will return an array with id as keys, and quantity as values. Otherwise use get, but never count if you want grouped results.

    0 讨论(0)
提交回复
热议问题