Laravel雄辩只返回foreach中第一个元素的返回结果?
我在order和orderItem之间有一个简单的hasMany
关系。我想要做的是获取类似订单项目的数量。这是我所做的:Laravel雄辩只返回foreach中第一个元素的返回结果?
$orderItems = $order->orderItems();
$distinctItems = $orderItems->groupBy('item_name')->distinct('item_name')->get();
foreach($distinctItems as $i){
$i['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
$order['items'] = $distinctItems;
但是,计数仅返回第一个订单项目,而其他项目返回0。我不知道为什么会发生这种情况。我也检查了where()
为第一个项目以外的项目返回null。
感谢您的帮助。
尝试只能使用集,第一GROUPBY ITEM_NAME,然后在每个项目上添加计数并返回新的集合这看起来像
$orderItems = $order->orderItems()->get();
$order['items'] = $orderItems->groupBy('item_name')->map(function($item) {
$i = $item->first();
$i->count = $item->count();
return $i;
});
是的,这是更整洁(: –
:)总是尝试使用框架的内置功能,他们只是在那里帮助我们写出整洁的代码.. :) –
试试看看这个代码。
$cnt = array();
foreach($distinctItems as $i){
$cnt[$i]['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();
}
print_r($cnt);
好了,没有什么改变,看到我上面的评论。 –
我不知道为什么会这样,但代替'$'['count'] = $ orderItems-> where('item_name','=',$ i-> item_name) - > count();'使用'$ i ['count'] = $ order-> orderItems() - > where('item_name','=',$ i-> item_name) - > count();'做的工作。解释会有所帮助。 –