Laravel多对多关系OrderBy

5
英译中:

我有两个处于多对多关系的模型。比如说用户(User)和角色(Role)。 我想根据角色中一个字段的升序/降序来对我的用户进行排序。

我的用户(User)和角色(Role)类:

class User extends Model
{
    public function roles()
{
    return $this->belongsToMany('App\Role','role_user');

}

class Role extends Model
{
    public function users()
{
    return $this->belongsToMany('App\User','role_user');

}

我可以对每个用户的角色进行排序,但无法对用户进行排序。
    $query = User::with(array('roles'=> function ($query)
    { 
       $query->select('role_name')->orderBy('role_name','asc'); 
    }))->get();

我也尝试过:
 $query = User::with(roles)->orderBy('role_name','asc')->get();

但是错误提示显示role_name列不存在。
理想结果应该像这样:
[
  {
    user_id:6
    roles: [
    "Admin",
    "Baby"
    ]
  },
  {
    user_id:2
    roles: [
    "Baby"
    ]
  },
  {
    user_id:11
    roles: [
    "Baby",
    "Cowboy"
    ]
  }
]

我会感激任何帮助。

你确定迁移已发布并创建了一个role_name列吗? - Leo
@Leo_Kelmendi 迁移没有什么特别的地方。枢轴表包含2个整数ID。 - Hirad Roshandel
啊,对了,检查代码后发现它只识别模型的列,而不是关系列...不过,我们不能反其道而行之吗?比如先从角色中获取数据... - Bagus Tesa
1
@BagusTesa 我最终为我的角色创建了一个不同的页面,并在那里查询它,因为我无法通过Eloquent实现此目标。 - Hirad Roshandel
1
嗨,@HiradRoshandel,虽然我相信一旦你拥有包含“用户”的集合“角色”,你可以使用map选择角色中的所有用户。好吧,至少现在你有了解决方法。 - Bagus Tesa
显示剩余5条评论
2个回答

1

由于用户可以有多个角色,我认为您可以将角色名称连接起来,然后按连接字符串对用户进行排序。请尝试以下方法:

User::selectRaw('group_concat(roles.name order by roles.name asc) as role_names, users.id')->
            join('role_user','users.id','=','role_user.user_id')->
            join('roles', 'roles.id','=','role_user.role_id')->
            groupBy('user_id')->
            orderBy('role_names','desc')->
            get()

1
请尝试在用户类中的roles()函数中进行以下修改,然后使用User获取它。
class User extends Model
{
    public function roles()
   {
      return $this->belongsToMany('App\Role','role_user')
                 ->selectRaw('id,'role_name')
                 ->orderby('role_name');

   }

}

$query = User::with(roles)->get();

希望这对你有用。

2
这将对角色进行排序,而不是用户。 - Hirad Roshandel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接