使用 Laravel/Eloquent 订购相关模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26130101/
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
Ordering Related Models with Laravel/Eloquent
提问by Alan Storm
Is it possible to use an orderBy
for an object's related models? That is, let's say I have a Blog Post model with a hasMany("Comments");
I can fetch a collection with
是否可以将 anorderBy
用于对象的相关模型?也就是说,假设我有一个博客帖子模型,hasMany("Comments");
我可以用
$posts = BlogPost::all();
And then run through each post, and display the comment's last edited date for each one
然后遍历每个帖子,并显示每个帖子的评论上次编辑日期
foreach($posts as $post)
{
foreach($post->comments as $comment)
{
echo $comment->edited_date,"\n";
}
}
Is there a way for me to set the order the comments are returned in?
有没有办法让我设置评论的返回顺序?
采纳答案by totymedli
The returned object from the relationship is an Eloquent instance that supports the functions of the query builder, so you can call query builder methods on it.
从关系中返回的对象是一个 Eloquent 实例,它支持查询构建器的功能,因此您可以在其上调用查询构建器方法。
foreach ($posts as $post) {
foreach ($post->comments()->orderBy('edited_date')->get() as $comment) {
echo $comment->edited_date,"\n";
}
}
Also, keep in mind when you foreach()
all posts like this, that Laravel has to run a query to select the comments for the posts in each iteration, so eager loadingthe comments like you see in Jarek Tkaczyk's answeris recommended.
另外,请记住,当您发布foreach()
所有此类帖子时,Laravel 必须运行查询以在每次迭代中选择帖子的评论,因此建议您像在Jarek Tkaczyk 的回答中看到的那样急切加载评论。
You can also create an independent function for the ordered comments like you see in this question.
您还可以像在这个问题中看到的那样,为有序评论创建一个独立的函数。
public function comments() {
return $this->hasMany('Comment')->orderBy('comments.edited_date');
}
And then you can loop them like you did in your original code.
然后您可以像在原始代码中那样循环它们。
回答by Jarek Tkaczyk
This is the correct way:
这是正确的方法:
BlogPost::with(['comments' => function ($q) {
$q->orderBy('whatever');
}])->get();
回答by Antonio Carlos Ribeiro
Yes:
是的:
$posts = BlogPost::with('comments')
->orderBy('comments_table_name.column_name')
->get();
And you can also set that in your relation:
你也可以在你的关系中设置它:
public comments()
{
$this->hasMany("Comments")->orderBy('comments.column_name');
}