2017-04-21 103 views
0

在用戶模型:如何在兒童模型中包含屬於父模型的兒童模型列?

public function role(){ 

    return $this->hasOne('App\Model\Roles','id','role_id'); 

} 

在角色型號:

public function user(){ 

    return $this->belongTo('App\Model\Users'); 

} 

在方法:

$query = Users::where('id', $id)->get(); 

我得到什麼(以JSON):

[{"id":2,"user_name":"hazardgeek","user_email":"[email protected]","user_phone":"*******","user_password":"*********","remember_token":"*****","role_id":2}] 

什麼我其實想要:

我希望role_title列來自Roles模型,而不是role_id來自Users表。 像這樣, ......user_password":"thesupernwa","remember_token":null,"role_title":"customer"}]

我該如何做到這一點?謝謝。

回答

1

在user.php的型號

public function User(){ 
    protected $appends = ['role_title']; 

    public function getRoleTitleAttribute(){ 
      $role = $this->getRelation('role'); 
      return !empty($role) ? $this->role->role_title : null; 
    } 
} 
+0

您的解決方案爲我提供了一組用戶模型中的角色模型。不會替換role_id列。 –

+0

您是否在user.php Model中添加了'protected $ appends = ['role_title'];'? –

+0

是的,我確實......但仍然沒有運氣 –

0

我結束了使用原始查詢來獲取正確的反應這個原始查詢

return DB::table('ctr_user') 
      ->select('ctr_user.id AS user_id','user_name','user_email','user_phone','user_password','remember_token','ctr_role.role_title AS title') 
      ->rightJoin('ctr_role', 'ctr_role.id','=','ctr_user.role_id') 
      ->where('ctr_user.id','=',$id) 
      ->get(); 

響應的回報是我需要用雄辯的準確響應。

但仍然如何?