沃梦达 / 编程问答 / php问题 / 正文

使用 Laravel/Eloquent 订购相关模型

Ordering Related Models with Laravel/Eloquent(使用 Laravel/Eloquent 订购相关模型)

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

问题描述

是否可以将 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 订购相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 Laravel/Eloquent 订购相关模型

基础教程推荐