[英]laravel how I can access data of model through another model
I am working with laravel 8 and I have the following table structure.我正在使用 laravel 8 并且我具有以下表结构。
id,name,email,password,...etc. id,name,email,password,...等。
id,bio,facebook,twitter,phone, user_id,...etc. id,bio,facebook,twitter,phone,user_id,...等。
id, title,details,image,user_id,....etc. id, title, details, image, user_id,....等。
and I create the following relation in Project model我在项目 model 中创建了以下关系
public function user(){
return $this->belongsTo(User::class,'user_id');
}
and have another relation in User model as following并且在用户 model 中有另一个关系如下
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
my question is how I can access user profile through project model?我的问题是如何通过项目 model 访问用户配置文件? I read about hasOneThrough relation but I don't understand how to apply it in my code
我阅读了 hasOneThrough 关系,但我不明白如何在我的代码中应用它
At the first you need to get a user then you can access the profile.首先,您需要获得一个用户,然后您才能访问该配置文件。 so:
所以:
Project::with('user.profile')->get()
Assuming in your user_profiles
table you have project_id
as a foreign key , Try:假设在您的
user_profiles
表中您有project_id
作为外键,请尝试:
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
);
}
Change this:改变这个:
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
To this:对此:
public function profile(){
return $this->belongsTo(UserProfile::class,'user_id');
}
Add this in your UserProfile model:将此添加到您的用户配置文件 model 中:
public function user(){
return $this->hasOne(User::class);
}
Get projects and try this to check if works:获取项目并尝试检查是否有效:
$project->user->profile;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.