简体   繁体   中英

retrieve data from multiple table

I have two tables (users and roles) have one to one relationship User model

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

the function in controller

   public function update_role($id)
{

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

the update_user view

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

but the retrieved data is only the user name from user table and not retrieve the user setting and user images from roles table

Try this

{{$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

Updated 2015-11-23

try to change the name of the variable in the controller so that it will have the right meaning when we bring it to the view, because you are bringing the user with 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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM