以laravel形式雄辩的mysql查询多对多关系

时间:2018-08-08 04:52:33

标签: laravel laravel-5

我有一个查询

SELECT product_id, SUM(quantity) as quantity FROM `order_product` GROUP BY product_id

order_product是产品和订单之间具有多对多关系的枢纽表

这是我的模特关系

订单模型

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity')->withTimestamps();
}

产品型号

public function orders()
{
    return $this->belongsToMany('App\Order')->withPivot('quantity')->withTimestamps();
}

我该如何以雄辩的方式使用它?

1 个答案:

答案 0 :(得分:1)

您可以这样获取它

$products = Product::with('orders')->get(); //always eager load orders relation

现在打印

foreach($products as $product){
      echo $product->orders->sum(pivot.quantity);
}