Laravel查询顺序嵌套关系



我有以下关系:

单元(HasMany)→用户→(BelongsTo)→位置

我试图返回一个包含用户的单元数组,其中用户按其位置排序。位置模型中的属性是"order",我想将其用作排序字段。我尝试了以下操作:

return Unit::query()->ordered()->with(['users' => function($query) {
$query->with(['position' => function($query) {
$query->orderBy('order');
}]);
}])->get();

不能只使用with()方法进行嵌套关系排序。您需要首先加入关系。所以代码应该是:

return Unit::query()->ordered()->with([
'users' => function ($query) {
$query->join('positions', 'positions.id', '=', 'users.position_id');
$query->orderBy('positions.order');
}
])->get();

或者另一种方式是使用laravel collection sortBy

$ordered_units = Unit::query()->ordered()->with(['users' => function($query) {
$query->with(['position' => function($query) {
$query->orderBy('order');
}]);
}])->get();
return $ordered_units->sortBy('users.position.order');

最新更新