【发布时间】:2017-04-16 23:18:18
【问题描述】:
我在 order 和 orderItems 之间有一个简单的hasMany 关系。我要做的是获取类似订单商品的数量。这就是我所做的:
$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。
感谢您的帮助。
【问题讨论】:
-
我不确定为什么会这样,但是使用
$i['count'] = $order->orderItems()->where('item_name', '=', $i->item_name)->count();而不是$i['count'] = $orderItems->where('item_name', '=', $i->item_name)->count();可以完成这项工作。解释会有所帮助。
标签: php laravel laravel-5 eloquent