Reputation: 2187
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.
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.
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.
Upvotes: 6
Views: 5621
Reputation: 403
Please try the below modification in roles() function in User Class and then fetch it with 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.
Upvotes: 2
Reputation: 2604
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()
Upvotes: 1