@Istom1n join the table in order to sort by related field, no other way to do it at the query level.
Aug 17, 2016
3
Level 4
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?
Level 53
2 likes
Please or to participate in this conversation.