1

I have a query

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

the order_product is the pivot table of products and orders in which they have many to many relationship

This is my model relationship

Order model

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

Product model

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

how can i use this in a form of laravel eloquent?

rkj
  • 8,067
  • 2
  • 27
  • 33
Beginner
  • 1,700
  • 4
  • 22
  • 42

1 Answers1

1

You can fetch it like this

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

Now print it

foreach($products as $product){
      echo $product->orders->sum(pivot.quantity);
}
rkj
  • 8,067
  • 2
  • 27
  • 33