You can just make a query for each sum/count. As it is just getting a single value for each, it should be that expensive. https://laravel.com/docs/8.x/queries#aggregates
Getting totals with paginated (and related) eloquent queries
Let's say I have a simple data structure with related tables: Customer has many Orders which in turn have many Products.
Say I'm presenting this in a table. An eloquent query would look something like:
$customersQuery = Customer::with(['orders', 'products'])
->withCount(['orders', 'products'])
->has('orders')
->where('created_at', '>=', $this->dateFrom);
When passing this to my blade view, I can use $customersQuery->paginate(50). This all works a treat.
But let's say I want to add a totals summary to my table. This would contain totals data for all records, not just the 50 in the pagination object. The total number of records in the pagination object is fine for a total count, but is there an accepted way of approaching how to get things like:
- sum of count of
Products from allOrders - sum of count of
Orders - sum of
totalvalue (an attribute of anOrder)
Would I need to ->get() all these first then use the collection sum methods? Could I select specific count columns/summed columns on a copy of the $customersQuery object? Or just make a whole new query that specifically only grabs the data I need?
Any hints or links to documentation/tutorials surrounding this would be great. Fwiw, this is in a Jetstream project, but doubt that makes much difference.
Please or to participate in this conversation.