本文介绍了使用Laravel/Eloquent订购相关模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将orderBy用于对象的相关模型?也就是说,假设我有一个Blog Post模型,该模型的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,"\n";
    }
}

我是否可以设置返回评论的顺序?

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,"\n";
    }
}

另外,请记住当您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订购相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:39