I am working with laravel 8 and I have the following table structure.
Users table
id,name,email,password,...etc.
usersProfile table
id,bio,facebook,twitter,phone, user_id,...etc.
projects table
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
CodePudding user response:
At the first you need to get a user then you can access the profile. so:
Project::with('user.profile')->get()
CodePudding user response:
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
);
}