Ordering Related Models with 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 订购相关模型
基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01