为了账号安全,请及时绑定邮箱和手机立即绑定

Eloquent 多对多关系上的汇总数据透视表字段

Eloquent 多对多关系上的汇总数据透视表字段

PHP
吃鸡游戏 2021-06-14 15:53:08
我有一个orders表、一个items表和一个名为的数据透视表item_order,它有两个自定义字段 ( price, quantity)。Order和之间的关系Item是belongsToMany。我正在尝试返回 id 为 的所有项目的计数1,其中父Order->status == 'received'. 对于我的生活,我无法弄清楚如何做到这一点。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');    }}
查看完整描述

2 回答

?
慕村9548890

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


它应该工作。


查看完整回答
反对 回复 2021-06-25
?
慕盖茨4494581

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');


查看完整回答
反对 回复 2021-06-25
  • 2 回答
  • 0 关注
  • 125 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信