Eloquent count() always returns 1

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I have the following query:

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

The count() method always returns 1 despite there being 20 rows to the results that are returned. Why might this be?

Here is the raw query from DB::getQueryLog():

select      count(*) as aggregate from     `items`         left join     `inventory` ON `items`.`id` = `inventory`.`item_id` group by `items`.`id` 

回答1:

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.



回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!