The resulting Collection has groupBy and sortBy methods to allow you to perform such operations - however, I would expect a small number of database queries to be more performant than iterating over a PHP array the same number of times.
Sep 14, 2022
3
Level 8
Is it possible to "mimic" group_by and order_by after a query?
I have a base query which needs to be done a few times with the only difference between them is the queryBy and orderBy columns. The results are supposed to be loaded into the same page. So I don't want to do separate queries because it will take time
For example, this is the base query:
MyModel::where()
->select(DB::raw('SUM(col1) as col1, SUM(col3) as col1, SUM(col3) as col3'))
But it has very similar variations:
MyModel::where()
->select(DB::raw('SUM(col1) as col1, SUM(col3) as col1, SUM(col3) as col3'))
->groupBy('col1')
->get()
or:
MyModel::where()
->select(DB::raw('SUM(col1) as col1, SUM(col3) as col1, SUM(col3) as col3'))
->groupBy('col1')->groupBy('col2')
->orderBy('col1')
->get()
or:
MyModel::where()
->select(DB::raw('SUM(col1) as col1, SUM(col3) as col1, SUM(col3) as col3'))
->groupBy('col1')->groupBy('col2')->groupBy('col3')
->orderBy('col1')->orderBy('col2')
->get()
So instead of calling the queries separately, can I somehow do "mimic" the groupBy and orderBy after the query? Or I should instead get the base data, and use PHP to do whatever I need?
Please or to participate in this conversation.