2016-08-19 167 views
1

我需要在标准Auth系统上让我的用户使用他们的角色(列出,而不是检查!)。
我somethink这样的:Laravel - 获取用户与他们的角色名称

$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' 
    } 
] 

我怎样才能做到这一点? 结构我的表:
用户
'身份证' '姓' ...等
角色
'身份证' '名'
user_roles
'USER_ID' 'role_id'

回答

1

尝试这个代码

应用/用户

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

控制器

use App/User; 

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

    } 
0

用户模型:

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

控制器:

use App/User; 

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