从多个表中检索数据

时间:2015-11-22 08:11:16

标签: php laravel select model

我有两个表(用户和角色)有一对一的关系 用户模型

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}}

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

1 个答案:

答案 0 :(得分: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}}