【问题标题】:Sum pivot table field on Eloquent many-to-many relationshipEloquent 多对多关系上的总和数据透视表字段
【发布时间】:2019-10-06 06:23:37
【问题描述】:

我有一个orders 表、一个items 表和一个名为item_order 的数据透视表,它有两个自定义字段(pricequantity)。 OrderItem 之间的关系是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');
    }
}

【问题讨论】:

  • 你的意思是所有的orders 和包含itemstatus == 'received'
  • 我正在尝试计算$order->status == 'received' 所在的特定商品的订购数量。我知道这与数据透视表quantity 字段的总和有关,但我不知道该怎么做。
  • 这是最新的失败尝试,只是为了让您了解我的想法:$items = Item::where('id', 1) ->whereHas('orders', function ($query) { $query->where('status', 'received'); }) ->selectRaw('item_order.amount as amount') ->sum('amount')->get();

标签: php laravel laravel-5 eloquent relationship


【解决方案1】:

试试这个:

$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,然后将相关的Orders 与具有Item 状态的Item,最后以sum 的pivot 属性获取单个价值。

它应该可以工作。

【讨论】:

    【解决方案2】:

    考虑到您知道项目的id,最高效的方法是直接查询item_order 表。我将为ItemOrder 创建一个pivot model 并定义belongsTo(Order::class) 关系并执行以下操作:

    $sum = ItemOrder::where('item_id', $someItemId)
        ->whereHas('order', function ($q) {
            return $q->where('status', 'received');
        })
        ->sum('quantity');
    

    【讨论】:

    • 我无法让 Pivot 模型正常工作:调用未定义的方法 App\ItemOrder::order() 我找不到关于需要包含哪些内容的非常好的文档在枢轴模型上。我确实在ItemOrder 模型上添加了适当的代码:public function orders() { return $this->belongsToMany(Order::class)->using(ItemOrder::class)->as('orderedItem')->withPivot('price', 'quantity'); } ` public function items() { return $this->belongsToMany(Item::class)->using(ItemOrder::class)-> as('orderedItem')->withPivot('price', 'quantity'); }`
    猜你喜欢
    • 2023-02-05
    • 2020-07-28
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多