2014-10-17 50 views
0

我已在中,返回JSON我的看法我的控制器方法如下:委託沒有找到用戶的角色

public function RolesForUser() 
    { 
     $userid = Input::get('userid'); 

     $assigned = DB::table('assigned_roles') 
       ->select(array('role_id')) 
       ->where('user_id', '=', $userid) 
       ->get(); 

     $user = User::find($userid); 
     $roles = $user->roles(); 

     $data = array('assigned' => $assigned, 'roles' => $roles); 
     return Response::json($data); 
    } 

返回以下(使用招檢查):

{"assigned":[{"role_id":"2"},{"role_id":"3"},{"role_id":"4"}],"roles":{}} 

的SQL語句使用查詢生成器返回正確的結果,但使用Entrust的方法(從Entrust Issue 34複製,在對我的用戶模型進行更改後)不返回任何角色。

我也試過this SO question的解決方案,但它只是給我一個SQL錯誤。

任何想法,我要錯了,我在Laravel 4.2.11?

我的用戶模型:

class User extends Eloquent implements UserInterface, RemindableInterface 
{ 
use HasRole; 

/** 
* The database table used by the model. 
* 
* @var string 
*/ 
protected $table = 'Users'; 

/** 
* The attributes excluded from the model's JSON form. 
* 
* @var array 
*/ 
protected $hidden = array('Password'); 

protected $primaryKey = 'UserID'; 

public $timestamps = false; 

/*Standard methods removed for brevity*/ 

public function roles() 
{ 
    return $this->hasMany('Role'); 
} 
} 
+0

看起來像用戶模型和它的角色之間的關係是以一種不適合你的方式設置的。你可以附加使用的關係方法或特徵嗎?謝謝! – hannesvdvreken 2014-10-17 10:49:29

+0

@hannesvdvreken - 我已經添加了我的用戶模型的相關位 – SteB 2014-10-17 11:11:35

回答

0

它看起來像您已經定義了roles方法不應該被定義。特徵HasRole的使用已經將roles關係添加到User模型。

看看其他的東西了HasRole添加到您的模型:https://github.com/Zizaco/entrust/blob/master/src/Entrust/HasRole.php

的角色()方法返回的關係。建議返回->roles->roles()->get()

希望這會有所幫助。

+0

有或沒​​有我自己的角色方法 - 它不返回任何東西。我也嘗試重命名它以避免潛在的命名衝突,但沒有喜悅。 – SteB 2014-10-17 11:53:47

+0

@SteB嘗試刪除()off $ roles = $ user-> roles();因爲這將返回一個查詢構建器對象而不是您期望的集合,因爲如果使用(),Eloquent通常允許您重新查詢關係。但請做hannesvdvreken說。 – 2014-10-17 12:35:44

+0

謝謝,我用更多的信息更新了我的答案。 – hannesvdvreken 2014-10-17 12:44:22