简体   繁体   中英

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM