I am working with laravel 8 and I have the following table structure.
id,name,email,password,...etc.
id,bio,facebook,twitter,phone, user_id,...etc.
id, title,details,image,user_id,....etc.
and I create the following relation in Project model
public function user(){
return $this->belongsTo(User::class,'user_id');
}
and have another relation in User model as following
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
my question is how I can access user profile through project model? I read about hasOneThrough relation but I don't understand how to apply it in my code
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:
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:
public function user(){
return $this->hasOne(User::class);
}
Get projects and try this to check if works:
$project->user->profile;
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.