How to Sum and Group by in Laravel using Eloquent
In this query, the goal is to utilize Eloquent to calculate the sum of a specific column while grouping the results based on another column. The example given in the question, where the sum of the no_of_pages column needs to be grouped by users_editor_id, serves as a practical illustration.
The initial attempt, which is provided in the question, suffers from a logical issue. Since sum() instantly runs the query and returns the result, grouping is attempted after the query has already been processed. Laravel does not support applying grouping after the query has been executed, hence the error.
To resolve this, it's necessary to alter the query structure. Instead of using groupBy() after sum(), start by grouping the results using groupBy('users_editor_id'). This will effectively create subqueries for each unique users_editor_id value.
Next, add a selectRaw() clause to specify the columns of interest from the grouped results. In this case, it's the aggregated sum: sum(no_of_pages) as sum.
Finally, use pluck() to extract only the sum and users_editor_id columns from the result. This will return an array with users_editor_id as the key and the corresponding sum as the value.
Here's the revised query:
Document::groupBy('users_editor_id') ->selectRaw('sum(no_of_pages) as sum, users_editor_id') ->pluck('sum','users_editor_id');
An alternative approach is to use a selectRaw() clause to include sum(no_of_pages) as an additional column in the subquery. However, this method produces a collection of pseudo-models that contain the original columns and the calculated sum as an additional field.
Document::groupBy('users_editor_id') ->selectRaw('*, sum(no_of_pages) as sum') ->get();
The above is the detailed content of How to Efficiently Sum and Group Data in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!