php - Sum relationship column before pagination in Laravel
I have a table that has products with price and a second table that has discounts with amount column. What I am looking for is a total of all products prices and all discounts amount from the query.The discount relation is a belongsTo
I am using the following to get my total product prices before my pagination.
$query->with(['discount']);
$total_cost = $query->sum('price');
$products = $query->paginate(25);
It works great for getting the $total_cost but I can't figure out how to get discounts and sum the amount column.
Answer
Solution:
Concept of eager loading with relationship will help with that.
$query->with(['discount' => function($another_query) {
$another_query->// do your sum here
} ]);
Source