How do I order a relationship in Laravel?

2019-08-09 18:23发布

问题:

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?

回答1:

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);
        }

}


标签: orm laravel-5