我有几个模型,例如用户、帖子、评论等。
在用户中,我有:
public function posts()
{
return $this->hasMany('Post');
}
我可以通过$customer->posts()->first()
获取第一篇文章,但是如果我想获取最新的文章怎么办?如我所见,没有 last()。
这由 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();
不会返回 User
模型。
要获得您所要求的,只需执行以下操作:
$customer->posts()->latest()->first();
关于php - Laravel Eloquent - 等同于 first() for last?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352672/