2015-11-22 21 views
0

检索数据我有两个表(用户和角色)具有一对一的关系 用户模型从多个表

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

在控制器

public function update_role($id) 
{ 

    $role = User::with('user_role')->find($id); 
    return view('update_role') -> with ('role',$role); 
} 

的update_user功能查看

{{$role -> name}} 
{{$role -> setting}} 
{{$role -> images}} 

但检索的数据只能从用户表中的用户名,而不是检索角色表中的用户设置和用户图像

+0

当你首先回应控制器中的$角色时,你会得到什么? – Ponce

+0

如果我返回$角色根据ID显示两个表中的所有数据, – user5565240

+0

当我在控制器中回显$角色时,我从表 – user5565240

回答

0

试试这个

{{$role->user_role->name}}   //this is if you are getting the role name 
{{$role->user_role->setting}}  //this is if you are getting the role setting 
{{$role->user_role->images}}  //this is if you are getting the role images 

更新2015年11月23日

尝试更改控制器中变量的名称,以便在我们将它带入视图时具有正确的含义,因为您正在为用户提供user_role。

//controller 
$user= User::with('user_role')->find($id); 
return view('update_role') -> with ('user',$user); 

//view - accessing it will be as simple as 
Username {{$user->username}}<br>    //accessing column in your user table 
Role  {{$user->user_role->name}}<br>  //accessing column in your user_role 
Setting {{$user->user_role->setting}}<br> 
Image {{$user->user_role->images}} 
+0

中获取所有数据,它与角色表成功工作,但用户表是work { $ role-> name}} – user5565240

+0

你能否澄清一下,如果你试图通过从用户的急切加载来访问user_role?如果是,那就用我指出的那个。否则,请您提供更多信息,以便我可以看到问题所在? – Ponce