2 回答
TA贡献1884条经验 获得超4个赞
试试这个:
$total_quantity = Item::find(1) // getting the Item
->orders() // entering the relationship
->with('items') // eager loading related data
->where('status', '=', 'received') // constraining the relationship
->get() // getting the results: Collection of Order
->sum('pivot.quantity'); // sum the pivot field to return a single value.
这里的策略是找到所需的对象Item,然后获取具有状态的Orderthis的相关s ,最终获取枢轴属性以获得单个值。Item'received'sum
它应该工作。
TA贡献1850条经验 获得超11个赞
考虑到您知道id项目的名称,最高效的方法是item_order直接查询表。我想创建一个枢纽模型的ItemOrder和定义belongsTo(Order::class)关系,并为此:
$sum = ItemOrder::where('item_id', $someItemId)
->whereHas('order', function ($q) {
return $q->where('status', 'received');
})
->sum('quantity');
- 2 回答
- 0 关注
- 125 浏览
添加回答
举报