我有一些模型,如用户,发布,评论等.
在用户中,我有:
public function posts()
{
return $this->hasMany('Post');
}
我可以通过$customer-> posts() – > first()获得第一篇帖子,但如果我想获得最新帖子怎么办?我看不到最后一个().
hasManyThrough关系进一步加剧了这种情况(遗憾的是我们继承了一个古怪的模式):
public function comments()
{
return $this->hasManyThrough('Comment', 'Post');
}
如果我尝试做$this-> comments() – > orderBy(‘comments.id’,’desc’) – > first();它返回一个User对象??
解决方法:
没有这个
// User model
$this->comments()->orderBy('comments.id', 'desc')->first();
不会返回用户模型.
为了得到你所要求的,只需这样做:
$customer->posts()->latest()->first();
标签:php,laravel,eloquent
来源: https://codeday.me/bug/20190725/1529984.html