I have a few queries that are almost identical but are different in the groupBy clauses.
These are some of the similar queries:
MyModel::select(DB::raw('SUM('col1') as col1, SUM('col2') as col2), SUM('col3') as col3'))
->groupBy('col1')
->get()
and
MyModel::select(DB::raw('SUM('col1') as col1, SUM('col2') as col2), SUM('col3') as col3'))->groupBy('col1')
->groupBy('col2')
->get();
and
MyModel::select(DB::raw('SUM('col1') as col1, SUM('col2') as col2), SUM('col3') as col3'))
->groupBy('col1')->groupBy('col2')->groupBy('col3')
->get();
Now I know that collections have groupBy and sortBy, but it doesn't work as expected here, since the collection returned from my queries is nested:
Illuminate\Database\Eloquent\Collection
#items: array: 1 [
0 => App\Models\MyModel
#attributes: array // <-- the actual data is here
so if I try to use it like in the docs, it won't work:
https://laravel.com/docs/9.x/collections#method-groupby
What I'm trying to achieve is this:
I want to have a single "base" query, and on top of this query, do the different groupBy's on the collection so that I only do 1 database query instead of multiple:
MyModel::select(DB::raw('SUM('col1') as col1, SUM('col2') as col2), SUM('col3') as col3'))->get()
And on top of it do the groupBy's
Is it possible?