Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nchornii's avatar

How I can query data from four tables?

I have four tables. And I need to run almost identical queries. Like this:

$model1 = Model1::selectRaw('table1.*, MAX(max_rating) as maxAverageRating')
    ->orderBy('max_rating', 'desc')
    ->groupBy('id')
    ->first();

$model2 = Model2::selectRaw('table2.*, MAX(max_rating) as maxAverageRating')
    ->orderBy('max_rating', 'desc')
    ->groupBy('id')
    ->first();

$model3 = Model3::selectRaw('table3.*, MAX(max_rating) as maxAverageRating')
    ->orderBy('max_rating', 'desc')
    ->groupBy('id')
    ->first();

$model4 = Model4::selectRaw('table4.*, MAX(max_rating) as maxAverageRating')
    ->orderBy('max_rating', 'desc')
    ->groupBy('id')
    ->first();

Is there any way to run this in one query WITHOUT joining?

0 likes
3 replies
jlrdw's avatar

Joins with group by is probably your best solution. Or write the results one at a time to a collection or array to get the data out you need. Many ways to handle it. Even 4 variables, then do whatever.

You already have $model1, $model2, $model3, $model4 since each have only one result, so just display as needed.

Please or to participate in this conversation.