mysql以laravel形式雄辩地进行多对多关系查询 [英] mysql query in a form of laravel eloquent many to many relationship
本文介绍了mysql以laravel形式雄辩地进行多对多关系查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个查询
SELECT product_id, SUM(quantity) as quantity FROM `order_product` GROUP BY product_id
order_product是产品和订单之间具有多对多关系的数据透视表
the order_product is the pivot table of products and orders in which they have many to many relationship
这是我的模特关系
订单模型
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('quantity')->withTimestamps();
}
产品型号
public function orders()
{
return $this->belongsToMany('App\Order')->withPivot('quantity')->withTimestamps();
}
我该如何以雄辩的Laravel形式使用它?
how can i use this in a form of laravel eloquent?
推荐答案
您可以这样获取它
$products = Product::with('orders')->get(); //always eager load orders relation
现在打印
foreach($products as $product){
echo $product->orders->sum(pivot.quantity);
}
这篇关于mysql以laravel形式雄辩地进行多对多关系查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文