I have problem with eloquent query. I am using eager loading (one to one Relationship) to get \'student\' With the \'exam\', Using the code
Student::with('exam')->get()->sortByDesc('exam.result');
This will sort the results of the query after eager loading using collection methods and not by a MySQL ORDER BY
.
When you eager load you can't use an ORDER BY
on the loaded relations because those will be requested and assembled as a result of a second query. As you can see it in the Laravel documentation eager loading happens in 2 query.
If you want to use MySQL's ORDER BY
you have to join the related tables.
As a workaround, you can run your query and sort the resulting collection with sortBy, sortByDesc or even sort. This solution has advantages and disadvantages over the join solution:
Advantages:
Disadvantages:
ORDER BY
with LIMIT
), you have to fetch everything, order it, then filter the ordered result, otherwise you will end up with only the filtered part being ordered (ordering will not consider the filtered out elements). So this solution is only acceptable when you would work on the whole data set anyway or the overhead is not a problem.