Sorting data with Eloquent

后端 未结 5 611
傲寒
傲寒 2021-01-11 12:49

I\'m new to laravel (switched from CI) and eloquent ORM is still a bit of a mystery at some point!

Here is my problem :

I\'d like to sort data from my db usi

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 13:10

    If you have the relationship defined in your user class then you can get all posts via the comments. It returns a Collection which provides the sortBy() and sortByDesc() functions. Both of these functions will accept a callback where you can choose the sort method yourself.

    $posts = $user->comments->post->sortByDesc(function($post) {
        return $post->created_at;
    });
    

提交回复
热议问题