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 IlluminateDatabaseEloquentRelationsHasMany */ public function orders(){ return $this->hasMany(Order::class); }
Model: Orders.php
/** * @return IlluminateDatabaseEloquentRelationsHasMany */ 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: id1 nameproductname price 1.00USD id2 nameproductname2 price 1.00USD
It must return sum of all product so it must return 2.00USD
@Jonas Staudenmeir
Advertisement
Answer
Using eloquent models without DB
Product::with(['orders' => function($query){ $query->sum('price'); }])->get();