2016-08-19 94 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();  
    } 
相關問題