Lubomir Stankov
Lubomir Stankov

Reputation: 179

Sum price of one to many relation ship (laravel)

i have problem with one to many relation ship! So im try to sum product prices so here is what i mean:

Model: Product.php

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders(){
    return $this->hasMany(Order::class);
}

Model: Orders.php

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function product(){
    return $this->belongsTo(Product::class);
}

So i want make smth like this: $var->product->price->sum();

My database if it needed:

Orders: id product_id|user_id| |-|----------|-------| |1|1 |1 | | | | |

And Products have only 4 columns: id,name,price,description

I mean that:

 products:

  id\1

  name\productname

  price \1.00USD

  id\2

  name\productname2

  price \1.00USD

It must return sum of all product so it must return 2.00USD

@Jonas Staudenmeir

Upvotes: 1

Views: 3176

Answers (4)

Bira
Bira

Reputation: 5506

In Laravel 6+ we can use like this, very straight forward

$total = $order->product->sum('price');

Upvotes: 0

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

Using eloquent models without DB

Product::with(['orders' => function($query){
   $query->sum('price');
}])->get();

Upvotes: 1

Lubomir Stankov
Lubomir Stankov

Reputation: 179

I find solution! So i make that

I use current relation ship like befor and i make that function in my order.php model

public function getTotalPrice() {

$orders = self::with('product')->get();

$total = 0;

foreach($orders as $order) {
 $total += $order->product->price;
} 

return $total;
}

Now i can use my function like obj and call it $var->getTotalPrice();

Upvotes: 0

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

try this QueryBuilder Query :

 DB::table('orders')
    ->leftJoin('products','orders.product_id','=','products.id')
    ->where('orders.user_id',Auth::user()->id)
    ->select('orders.*','products.*',DB::raw("SUM(products.price) as order_total"))
    ->groupBy('orders.product_id')
    ->get();

Upvotes: 2

Related Questions