Laravel Eloquent - 最后相当于 first() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25352672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent - equivalent to first() for last?
提问by StackOverflowed
I have a few models such as User, Post, Comment, etc.
我有一些模型,例如用户、帖子、评论等。
In the User, I have:
在用户中,我有:
public function posts()
{
return $this->hasMany('Post');
}
I can get the first post via $customer->posts()->first()
, but what if I want to get the latest Post? There is no last() as I can see.
我可以通过 获得第一篇文章$customer->posts()->first()
,但是如果我想获得最新的文章怎么办?正如我所见,没有 last() 。
This is further compounded by a hasManyThrough relationship (unfortunately we inherited a wacky schema):
hasManyThrough 关系进一步加剧了这种情况(不幸的是,我们继承了一个古怪的模式):
public function comments()
{
return $this->hasManyThrough('Comment', 'Post');
}
If I try to do an $this->comments()->orderBy('comments.id', 'desc')->first();
it returns a User object??
如果我尝试执行$this->comments()->orderBy('comments.id', 'desc')->first();
它返回一个用户对象?
回答by Jarek Tkaczyk
No, this
没有这个
// User model
$this->comments()->orderBy('comments.id', 'desc')->first();
won't return User
model.
不会返回User
模型。
And to get what you asked for, simply do this:
要获得您所要求的,只需执行以下操作:
$customer->posts()->latest()->first();
回答by The Alpha
You said There is no last() as I can see
, but actually there is a last()
method available as well, so you can use it like:
您说There is no last() as I can see
,但实际上也有一种last()
方法可用,因此您可以像这样使用它:
$customer->posts->last();
Notice that, it's not $customer->posts()->last()
like you've used in your example using first()
.
请注意,这$customer->posts()->last()
与您在示例中使用的first()
.