2015-09-07 28 views
0

在我的數據庫中,我有兩個模型,用戶和角色定義爲多關係,我試圖在laravel中編寫一個代碼,角色表並從用戶表中獲取所有用戶全名。在laravel中使用php返回多關係中的特定列

我已經定義,看起來像這樣的路線:

Route::get('roleUser/{role}', '[email protected]'); 

中,我通過角色名吧,你看上面

在我RoleController,我定義的方法角色名做工作

public function RoleNames($role) 
{ 


    $idrole = Role::where('name', '=', $role)->first()->id; 
    //$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->first()->id; 
    $iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(array('id')); 

    $usersUnderRole = array(); 
    foreach ($iduser as $idusers) { 

     $usersUnderRole = array_add($usersUnderRole, $idrole, $idusers); 

     $full_name = DB::table('users')->where('id', '=', $idusers)->get()->full_name; 
    } 
     return $this->respond([ 
      'result' => $this -> roleTransformer->transform($full_name) 

     ]); 
} 

此代碼是爲了採取從rolesrole_id,並得到相應的user_ids由樞軸表assigned_roles,使他們在一個數組並獲取相應full_names,但它說這個錯誤:

  • Object of class stdClass could not be converted to string

如何得到它的工作有什麼建議?

+0

'$ FULL_NAME = DB ::表( '用戶') - >在哪裏( '身份證',「= ',$ idusers) - > get() - > full_name;'這部分很奇怪,查詢生成器'get'將返回一個集合,而不是一行。你是不是指'...-> first() - > full_name'? – Iamzozo

+0

我試圖讓所有與指定角色相關的用戶名,不僅是第一個用戶@lamzozo –

+0

雄辯不玩?你堅持查詢生成器嗎?這可以通過幾行雄辯來完成。 – Iamzozo

回答

0

除了@lamzazo提供的解決方案,還有另一種方式去與答案:

 $role2 = Role::where('name', '=', $role)->first(); 

     $idrole = Role::where('name', '=', $role)->first()->id; 
     //$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole); 
     $user = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(); 
     // $user = DB::table('users')->where('id', '=', $iduser); 


     // return $this->respond($iduser[0]->user_id); 


     $userArray = array(); 

     $i=0; 

     foreach ($user as $users) { 
      $iduser= $users->user_id; 
      $allusers = User::where('id', '=', $iduser)->get(array('id', 'full_name')); 
      $userArray = array_add($userArray, $i . '', $allusers); 
      $i++; 

     } 



     return $this->respond([ 
       'result' => $this -> roleTransformer->testTransform($role2, $userArray) 

     ]); 
0

這會給你所有屬於誰給定角色的用戶:

$role_id = 3; 

$result = DB::table('role_user') 
    ->select('users.full_name') 
    ->where('role_user.role_id', $role_id) 
    ->leftJoin('users', 'users.id', '=', 'role_user.user_id') 
    ->get(); 

var_dump($result); 
+0

非常感謝你,這實際上是有益的@lamzozo –

0

$ full_names = DB ::表( '用戶') - >在哪裏( '身份證', '=',$ idusers) - >列表( 'users.full_name');