Laravel eloquent按关系模型上的角色名称排序

时间:2023-04-10
本文介绍了Laravel eloquent按关系模型上的角色名称排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我遇到了一个问题,我必须根据模型的关系数据对模型集合进行排序/排序.

I'm stuck with a problem where I have to sort / order a collection of models by their relationship's data.

我的设置如下:

型号:UserTeamTeamUserRole

TeamUser 模型是一个数据透视模型/表(包含 user_idteam_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按关系模型上的角色名称排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Laravel 5 雄辩的 whereIn 下一篇:基于多个 ID 检索 Laravel 模型结果

相关文章