Laravel 按关系字段查询生成器顺序

Laravel Query Builder order by relationship field

我正在尝试按以下方式按关系字段排序:

Post::with(['comments' => function($query) {
    $query->orderBy('some_comment_field', 'desc');
}]);

但这行不通。我该怎么做?

我用Laravel 5.8.

如果您想按评论字段排序,您应该使用 join:

将其添加到主 select
Post::with(['comments'])->join('comments','posts.id','comments.post_id')
->select(['posts.*','comments.some_comment_field'])
->orderby('comments.some_comment_field', 'desc')->get();

你可以省略预加载评论和select你想要的评论字段,你也可以使用别名来获得清晰的列名

示例 1

// in post model
public function comments()
{
    return $this->hasMany('App\Comment', 'post_id', 'id');
}

// in post controller
Post::with(['comments' => function($query) {
    $query->orderBy('date', 'desc');
}])->get();

示例 2

// in post model
public function comments()
{
    return $this->hasMany('App\Comment', 'post_id', 'id')
        ->orderBy('date', 'desc');
}

// in post controller
Post::with('comments')->get();