问题描述
是否可以将 orderBy 用于对象的相关模型?也就是说,假设我有一个带有 hasMany("Comments"); 的博客帖子模型,我可以使用
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
$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,"
";
}
}
有没有办法让我设置评论的返回顺序?
Is there a way for me to set the order the comments are returned in?
推荐答案
关系返回的对象是一个 Eloquent 实例,支持查询构建器的功能,因此可以在其上调用查询构建器的方法.
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.
foreach ($posts as $post) {
foreach ($post->comments()->orderBy('edited_date')->get() as $comment) {
echo $comment->edited_date,"
";
}
}
另外,当你 foreach() 像这样的所有帖子时,请记住,Laravel 必须运行查询以在每次迭代中选择帖子的评论,所以 热切加载 就像您在 推荐使用 Jarek Tkaczyk 的答案.
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 loading the comments like you see in Jarek Tkaczyk's answer is recommended.
您也可以像在这个问题中看到的那样,为有序评论创建一个独立的函数.一>.
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.
这篇关于使用 Laravel/Eloquent 订购相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)