Laravel Eloquent - 相当于第一个()?

问题描述 投票:3回答:2

我有一些模型,如用户,发布,评论等。

在用户中,我有:

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对象?

php laravel eloquent
2个回答
6
投票

没有这个

// User model
$this->comments()->orderBy('comments.id', 'desc')->first();

将不会返回User模型。

为了得到你所要求的,只需这样做:

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

2
投票

你说There is no last() as I can see,但实际上也有一个last()方法,所以你可以使用它像:

$customer->posts->last();

请注意,它不是像你在使用$customer->posts()->last()的示例中使用的那样使用first()

© www.soinside.com 2019 - 2024. All rights reserved.