Laravel Eloquent——相当于first()表示last


Laravel Eloquent - equivalent to first() for last?

我有几个模型,如用户,帖子,评论等。

在User中,我有:

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 model
$this->comments()->orderBy('comments.id', 'desc')->first();

将不返回User模型。

要得到你想要的,只需这样做:

$customer->posts()->latest()->first();