Eloquent count() 总是返回 1 [英] Eloquent count() always returns 1
本文介绍了Eloquent count() 总是返回 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询:
Item::select(['items.id', 'inventory.quantity'])
->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
->groupBy('items.id')
->count();
count()
方法总是返回 1,尽管返回的结果有 20 行.为什么会这样?
The count()
method always returns 1 despite there being 20 rows to the results that are returned. Why might this be?
这是来自 DB::getQueryLog()
的原始查询:
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`
推荐答案
是的,count
始终只返回 1 行.
Yes, count
returns only 1 row, always.
您可能想要:
Item::select(['items.id as id', 'inventory.quantity as quantity'])
->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
->groupBy('items.id')
->lists('quantity', 'id');
这将返回一个以 id
作为键,quantity
作为值的数组.否则使用 get
,但如果你想要分组结果,不要使用 count
.
this will return an array with id
as keys, and quantity
as values. Otherwise use get
, but never count
if you want grouped results.
这篇关于Eloquent count() 总是返回 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文