Eloquent eager load Order by

后端 未结 7 2118
花落未央
花落未央 2020-11-27 13:56

I have problem with eloquent query. I am using eager loading (one to one Relationship) to get \'student\' With the \'exam\', Using the code

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 14:46

    tl;dr

    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.

    Explanation

    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:

    • You keep Eloquent functionality.
    • Shorter and more intuitive code.

    Disadvantages:

    • Sorting will be done by PHP instead of the database engine.
    • You can sort only by a single column, unless you provide a custom closure for the sorter functions.
    • If you need only a part of the ordered results of a query (e.g. 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.

提交回复
热议问题