Level 27
@erron You have to use a join in order to achieve what you want. Right now you are simply ordering the departments and since there is only one for each user nothing happens.
1 like
I have two models: User and Department
I want to sort the users based on department name with pagination. But results are still not sorted.
$sortType = request("sortType") ?? "asc";
$users = User::with(["department" => function ($query) use ($sortType) {
$query->orderBy("name", $sortType);
}]);
$users = $users->paginate(10);
Thanks to @corvs for the idea. I managed to solve it by this:
$users = $users->leftJoin('departments', 'users.department_id', '=', 'departments.id')
->select('users.*')
->orderBy('departments.name', $sortType);
$users = $users->paginate(10);
Please or to participate in this conversation.