Laravel orderBy 上的关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18143061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:35:29  来源:igfitidea点击:

Laravel orderBy on a relationship

laravellaravel-4

提问by PrestonDocks

I am looping over all comments posted by the Author of a particular post.

我正在遍历特定帖子的作者发布的所有评论。

foreach($post->user->comments as $comment)
    {
        echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
    }

This gives me

这给了我

I love this post (3)
This is a comment (5)
This is the second Comment (3)

How would I order by the post_id so that the above list is ordered as 3,3,5

我将如何按 post_id 排序,以便将上述列表排序为 3,3,5

回答by Rob Gordijn

It is possible to extend the relation with query functions:

可以使用查询函数扩展关系:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

[评论后编辑]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

默认用户模型 + 简单控制器示例;获取评论列表时,只需应用基于 Input::get() 的 orderBy()。(一定要进行一些输入检查;))

回答by agm1984

I believe you can also do:

我相信你也可以这样做:

$sortDirection = 'desc';

$user->with(['comments' => function ($query) use ($sortDirection) {
    $query->orderBy('column', $sortDirection);
}]);

That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:

这允许您在每个相关评论记录上运行任意逻辑。你可以在里面放一些东西,比如:

$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);