描述了如何通过另一个模型访问一个模型的数据



我正在使用laravel 8,我有以下表结构。

用户表id、姓名,电子邮件,密码,等。

usersProfile表id、生物、facebook、twitter、电话、user_id,…等等。

项目表id、标题、细节,图像,user_id,…等等。

和我在Project model

中创建如下关系
public function user(){
return $this->belongsTo(User::class,'user_id');
}

和User模型中的另一个关系如下

public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}

我的问题是如何通过项目模型访问用户配置文件?我读过关于hasOneThrough关系,但我不明白如何在我的代码中应用它

首先需要获得一个用户,然后才能访问配置文件。所以:

Project::with('user.profile')->get()

假设在user_profiles表中,project_id作为外键, Try:

public function userProfile()
{
return $this->hasOneThrough(
UserProfile::class,
Project::class,
'user_id', // Foreign key on the projects table
'project_id', // Foreign key on the user_profiles table
'id', // Local key on the users table
'id' // Local key on the projects table
);
}

修改如下:

public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}

:

public function profile(){
return $this->belongsTo(UserProfile::class,'user_id');
}

将此添加到您的UserProfile模型中:

public function user(){
return $this->hasOne(User::class);
}

获取项目并尝试检查是否有效:

$project->user->profile;