Istom1n's avatar

Eager loading can't orderBy

Hello! My data:

Journal->hasMany(Article::class);

Journal:
- id
- issue_number
- title

Article:
- id
- title
- content
- journal_id

I want to sort my articles by journal issue_number, I use eager loading for it.

$articles = Article::with(['journal' => function ($query) {
            $query->orderBy('issue_number', 'desc');
        }])->get();

But it does not sort

$articles = Article::with('journal')->get()->sortByDesc('journal.issue_number');

It works!

My problem is that I would like to use pagination and the last way I get a collection. Maybe I don't understand how callback of eager loading works?

0 likes
3 replies
JarekTkaczyk's avatar
Level 53

@Istom1n join the table in order to sort by related field, no other way to do it at the query level.

2 likes
JarekTkaczyk's avatar

@Istom1n Thing is, these are 2 separate queries (each eager loaded relation is another query as a matter of fact), so you cannot in any way reference ordering of the 2nd query within the 1st query.

Your code, that is taken from the docs, will work but on the related query only. And in your case (belongsTo) it doesn't make any difference at all, because there's just 1 related model anyway.

If you tried it eg. on hasMany, it would be fine:

Post::with(['comments' => function ($q) {
    $q->latest();
})->get();

here each post's comments will be ordered by created_at desc.

1 like

Please or to participate in this conversation.