Laravel查询生成器“按关系排序”字段

Laravel查询生成器“按关系排序”字段,laravel,eloquent,eloquent-relationship,Laravel,Eloquent,Eloquent Relationship,我尝试按关系字段按以下方式排序: Post::with(['comments' => function($query) { $query->orderBy('some_comment_field', 'desc'); }]); 但这不起作用。我该怎么做 我使用的是Laravel 5.8。如果您想按注释字段排序,应使用连接将其添加到主选择中: Post::with(['comments'])->join('comments','posts.id','comments.p

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

Post::with(['comments' => function($query) {
    $query->orderBy('some_comment_field', 'desc');
}]);
但这不起作用。我该怎么做


我使用的是Laravel 5.8。

如果您想按注释字段排序,应使用连接将其添加到主选择中:

Post::with(['comments'])->join('comments','posts.id','comments.post_id')
->select(['posts.*','comments.some_comment_field'])
->orderby('comments.some_comment_field', 'desc')->get();
您可以省略“快速加载注释”并选择所需的注释字段,还可以使用别名来获取清晰的列名称示例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();