Beginner
Beginner

Reputation: 1740

mysql query in a form of laravel eloquent many to many relationship

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?

Upvotes: 1

Views: 113

Answers (1)

rkj
rkj

Reputation: 8287

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

Upvotes: 1

Related Questions