Tags
Laravel
Asked 3 years ago
17 Jun 2021
Views 344
Luigi

Luigi posted

Eloquent eager load Order by

Eloquent eager load Order by
debugger

debugger
answered Feb 28 '23 00:00

When using Eloquent's eager loading to retrieve related models , you can specify the order in which the related models should be loaded using the orderBy method.

To do this, you can chain the orderBy method to the eager loading call, like this:



$posts = App\Post::with(['comments' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();

In this example, the Post model is being loaded with its related Comment models, ordered by the created_at attribute in descending order.

You can also order by attributes of the parent model or any other related model by chaining additional orderBy calls to the eager loading call:

$posts = App\Post::with(['comments' => function ($query) {
    $query->orderBy('created_at', 'desc');
}, 'user' => function ($query) {
    $query->orderBy('name', 'asc');
}])->orderBy('published_at', 'desc')->get();

In this example, the Post model is being loaded with its related Comment models ordered by created_at and its related User models ordered by name. The resulting collection of Post models is then ordered by the published_at attribute in descending order.
Post Answer