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