How do I order a relationship in Laravel?

2019-08-09 18:10发布

I saw this question in StackOverflow, but I could not answer it because it was mistakenly marked as duplicate. However $user->posts is not the same as Posts::all(). So if you have User and Post, how do you sort the posts?

标签: orm laravel-5
1条回答
叼着烟拽天下
2楼-- · 2019-08-09 19:04

Ya, answering my own question just to help out.

class User extends Model implements ... {
    public function posts(){
            return $this->hasMany('App\Post');
        }

    public function recentPosts($limit = 5){
            return $this->posts
                        ->sortByDesc(function($post){
                            return $post->created_at;
                        })->take($limit);
        }

}
查看更多
登录 后发表回答