Laravel在关系模型上按角色名称雄辩地排序 [英] Laravel eloquent sort by role name on relationship model
问题描述
我遇到了一个问题,我必须根据关系数据对模型集合进行排序/订购。
I'm stuck with a problem where I have to sort / order a collection of models by their relationship's data.
我已经设置好了:
型号:
用户
,团队
, TeamUser
,角色
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
?
在团队中对用户进行排序我在说 users()$
团队
模型中的c $ c>关系(有关代码示例,请参阅下面的内容。)
一些用户具有 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 \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function team()
{
return $this->belongsToMany('App\Team', 'team_users', 'user_id', 'team_id');
}
Team.php
/**
* User relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany('App\User', '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', '=', 'app\Models\User');
})
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name')
->get();
我已经尝试过了,它工作正常。
i have tried it, it work just fine.
请注意,如果您想按多列进行排序,则可以根据需要添加'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在关系模型上按角色名称雄辩地排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!