【问题标题】:mysql query in a form of laravel eloquent many to many relationshipmysql 以 laravel eloquent 多对多关系的形式查询
【发布时间】:2019-01-15 06:08:42
【问题描述】:

我有一个问题

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();
}

如何以 laravel eloquent 的形式使用它?

【问题讨论】:

  • order_productorderproduct 之间的数据透视表,对吗?
  • 是的先生......
  • 这是在 order_product 数据透视表中获取所有结果的正确方法吗?因为我为这个数据透视表做了一个模型,然后只获取所有的结果。
  • 现在好了..
  • 我已经添加了答案检查它

标签: laravel laravel-5


【解决方案1】:

你可以这样获取它

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

现在打印出来

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

【讨论】:

猜你喜欢
  • 2017-11-03
  • 2014-10-31
  • 2019-06-13
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 2013-05-15
  • 2014-09-27
  • 1970-01-01
相关资源
最近更新 更多