Laravel - 获取用户角色名称

时间:2016-08-19 13:04:03

标签: mysql laravel eloquent

我需要让我的用户在标准Auth系统上使用他们的角色(列表,而不是检查!) 我这样想:

$users = DB::table('users')
            ->join( 'user_roles', 'users.id', '=', 'user_roles.user_id' )
            ->select('id', 'first_name', 'role_id')
            ->get();

我得到了这个:

array:2 [▼
  0 => {#552 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"role_id": 1337
  }
  1 => {#553 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"role_id": 100
  }
]

但我需要这个:

array:2 [▼
  0 => {#552 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"roles": 'Admin, AnotherRole'
  }
]

我该怎么做? 我桌子的结构:
用户
'ID' '名字' ......等 的角色
'ID' “名”
user_roles
'用户身份' 'ROLE_ID'

3 个答案:

答案 0 :(得分:2)

用户模型:

public function roles()
{
    return $this->belongsToMany('App\Role');
}

控制器:

 use App/User;

  public funtion index(User $user)  {
    $users=  User::with('roles')->get();    
  }

答案 1 :(得分:1)

在您的用户类中添加以下内容:

   public function roles()
   {
       return $this->belongsToMany('App\Role');
   }

现在你可以做到

$user->roles

访问角色。

文档:https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

答案 2 :(得分:1)

尝试此代码

应用/用户

public function roles()
{
    return $this->belongsToMany('App\Role');
}

控制器

  use App/User;

  public funtion getUsers(User $user)  {
    $getUsersWithRole =  $user->with('roles')->get();
    dd($getUsersWithRole);

  }
相关问题