問題描述
我遇到了一個問題,我必須根據模型的關系數據對模型集合進行排序/排序.
I'm stuck with a problem where I have to sort / order a collection of models by their relationship's data.
我的設置如下:
型號:User
、Team
、TeamUser
、Role
TeamUser
模型是一個數據透視模型/表(包含 user_id
和 team_id
.如果值得一提,我也使用 spatie/laravel-permissions角色.
The TeamUser
model is a pivot model / table (containing user_id
and team_id
.
If it's worth mentioning I am also using spatie/laravel-permissions for the roles.
如果我想按role.name
對團隊中的用戶進行排序,我該怎么做?我正在談論 Team
模型中的 users()
關系(請參閱代碼示例的進一步內容).一些用戶具有 team-leader
角色,大多數用戶具有 team-seller
角色.我試過做一個普通的 ..->sortBy('role.name')
但這似乎不起作用.如果有人可以幫助我,請提前致謝.
How would I go forth when I want to sort the users in a team by their role.name
?
I'm talking about the users()
relation in the Team
model (see further down for code sample).
Some users have the role team-leader
and most have the role team-seller
. I've tried doing a ordinary ..->sortBy('role.name')
but that doesn't seem to work. Thanks in advance if anyone could help me out.
User.php
/**
* Team relation
*
* @return IlluminateDatabaseEloquentRelationsBelongsToMany
*/
public function team()
{
return $this->belongsToMany('AppTeam', 'team_users', 'user_id', 'team_id');
}
Team.php
/**
* User relation
*
* @return IlluminateDatabaseEloquentRelationsBelongsToMany
*/
public function users()
{
return $this->belongsToMany('AppUser', 'team_users', 'team_id', 'user_id')->withTimestamps();
}
推薦答案
如果要根據嵌套關系列對結果進行排序,則必須使用連接鏈:
if you want to order the result based on nested relation column, you must use a chain of joins:
$values = Team::query()
->leftJoin('users', 'users.team_id', '=', 'teams.id')
->leftJoin('model_has_roles', function ($join) {
$join->on('model_has_roles.model_id', '=', 'users.id')
->where('model_has_roles.model_type', '=', 'appModelsUser');
})
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name')
->get();
我試過了,效果很好.
請注意,如果您想按多列排序,您可以根據需要添加 'orderBy' 子句:
please note that if you want to order by multiple columns you could add 'orderBy' clause as much as you want:
->orderBy('roles.name', 'DESC')->orderby('teams.name', 'ASC') //... ext
這篇關于Laravel eloquent按關系模型上的角色名稱排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!