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 订购相关模型
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
