简体   繁体   English

使用laravel中的关系从两个表中获取用户信息

[英]Get user info from two tables using relationships in laravel

I have model user and user_data. 我有模型用户和用户数据。 I want to take some data from user and user data. 我想从用户和用户数据中获取一些数据。 My code looks like: 我的代码如下:

User model: 用户模型:

public function user_data()
{
    return $this->hasMany('App\Models\UserData', 'user_id');
}

public function getUserById($id)
{
    $user = User::findOrFail($id);

    return $user;
} 

UserData model: UserData模型:

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

User controller 用户控制器

public function getUser($id) 
{
    //$user = $this->model->getUserById($id);

    $user = User::with('user_data')->find(3);

    dd($user->sex);
    return view('user', compact('user'));
}

How I can get data from two tables? 如何从两个表中获取数据? When i dump sex i get null, but I have it in db. 当我转储我性时,我得到空,但我在数据库中。

you have to add also the local key in the relationship like this 您必须像这样在关系中添加本地密钥

public function user_data()
{
    return $this->hasMany('App\Models\UserData', 'user_id','your local key');
}

$user = User::with('user_data')->where('id',$id)->first(); // Get the data like this

After that you can check what is it in like this 之后,您可以像这样检查它的内容

$user->user_data[0]->sex // Not $user->sex

If it's not working try to swap the foreign key and local key places. 如果不起作用,请尝试交换外键和本地键位置。

Also you have to take the data like this 你也必须像这样取数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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