[英]Sum pivot table field on Eloquent many-to-many relationship
I have an orders
table, an items
table, and a pivot table called item_order
which has two custom fields ( price
, quantity
). 我有一个orders
表,一个items
表和一个名为item_order
的数据透视表,它有两个自定义字段( price
, quantity
)。 The relationship between Order
and Item
is belongsToMany. Order
和Item
之间的关系是belongsToMany。 I'm trying to return the count of all items with an id of 1
, where the parent Order->status == 'received'
. 我正在尝试返回id为1
的所有项的计数,其中父Order->status == 'received'
。 For the life of me, I can't figure out how to do this. 对于我的生活,我无法弄清楚如何做到这一点。
class Order extends Model
{
public function items()
{
return $this->belongsToMany(Item::class)->withPivot('price', 'quantity');
}
}
class Item extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class)->withPivot('price', 'quantity');
}
}
Try this: 尝试这个:
$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.
The strategy here is to find the desired Item
to then get the related Order
s to this Item
that has a 'received'
status, to finally sum
the pivot attribute in order to get a single value. 这里的策略是找到所需的Item
,然后获得具有'received'
状态的此Item
的相关Order
,以最终对枢轴属性sum
以获得单个值。
It should work. 它应该工作。
Considering you know the id
of the item, most performant way would be to query item_order
table directly. 考虑到你知道项目的id
,最有效的方法是直接查询item_order
表。 I would create a pivot model for ItemOrder
and define the belongsTo(Order::class)
relationship and do this: 我将为ItemOrder
创建一个pivot模型并定义belongsTo(Order::class)
关系并执行以下操作:
$sum = ItemOrder::where('item_id', $someItemId)
->whereHas('order', function ($q) {
return $q->where('status', 'received');
})
->sum('quantity');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.