In Laravel, we can use the withSum method with combination hasManyThrough relationship with the where clause to calculate the sum of related records from while applying conditions to the related records. Here's how you can do it:
Assuming you have the same example of Client, Order, OrderDetail models where you want to calculate the sum of qnt in OrderDetail populations for a specific client but with additional conditions :
// Order.php model
class Order extends Model
{
protected $fillable = [
'user_id',
'status',
];
}
// OrderDetail .php model
class OrderDetail extends Model
{
protected $fillable = [
'order_id',
'product_id',
'quantity',
'amount'
];
}
Now, define the hasManyThrough relationship in the Client model:
// Client.php model
class Client extends Model
{
public function ordersDetails(){
return $this->hasManyThrough(OrderDetail::class,Order::class,'user_id','order_id','id','id')
->where('orders.status',Order::COMPLETED);
}
}
To calculate the sum of quantity for a specific clients, you can use the withSum method in your query:
$clients = Client::withSum(['ordersDetails'],'quantity')->get();
// you can see column order_details_sum_quantity
Top comments (0)