[英]Laravel many-to-many relationship OrderBy
I have 2 models in a Many to Many relationship. 我有两个模型,多对多关系。 Let's say User and Role. 让我们说用户和角色。 I want to sort my users based on the ASC/DESC of a field in Role. 我想根据Role中字段的ASC / DESC对用户进行排序。
My User & Role classes: 我的用户和角色类:
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');
}
I can sort the roles in each user but I cant sort the users 我可以对每个用户中的角色进行排序,但我无法对用户进行排序
$query = User::with(array('roles'=> function ($query)
{
$query->select('role_name')->orderBy('role_name','asc');
}))->get();
I have also tried: 我也尝试过:
$query = User::with(roles)->orderBy('role_name','asc')->get();
But the error says column role_name does not
exist. 但错误表示column role_name does not
存在。
Ideal result should look like this: 理想的结果应如下所示:
[
{
user_id:6
roles: [
"Admin",
"Baby"
]
},
{
user_id:2
roles: [
"Baby"
]
},
{
user_id:11
roles: [
"Baby",
"Cowboy"
]
}
]
I'd appreciate any help. 我很感激任何帮助。
As user can have many roles i think you can concatenate role names and then order users by concatenated string. 由于用户可以拥有多个角色,我认为您可以连接角色名称,然后通过连接字符串对用户进行排序。 Try this: 尝试这个:
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()
Please try the below modification in roles() function in User Class and then fetch it with User. 请在User Class中的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();
Hope this will be useful for you. 希望这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.