1
votes

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

4
You have only one item per order? If not then you may need many to many relation with intermediate table. Dociamab.in
Yes i have only one item per orderLubomir Stankov
What exactly do you want to sum? What's $var?Jonas Staudenmeir
If you have only one product then why use sum? You may try $order->product->price;. If you have quantity field in the order you may multiply the price with that.iamab.in
hmm.. Can u explain me how it will be done with many to many relation ships?Lubomir Stankov

4 Answers

2
votes

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();
0
votes

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

0
votes

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

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

Using eloquent models without DB

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