Reputation: 6639
Am still new to laravel
I have the following tables
user
id
first_name
last_name
educations
id,
user_id //references user id
type
Now in my user
model i would like to get a specific users educations which can be many
so a user can have many educations but each education belongs to a single user.
So in my user
model i have
public function education()
{
return $this->hasMany('App\ApplicantEducation','id','user_id');
}
In my Education
model i have
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
But the above fails, I cannot retrieve user specific educations
Where am i going wrong?
Upvotes: 1
Views: 48
Reputation: 21681
You should try this:
Education Model
public function user()
{
return $this->belongsTo('App\User','user_id);
}
User Model
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}
Upvotes: 1
Reputation: 1301
Here,
$this->hasMany('App\ApplicantEducation','id','user_id');
In above statement first argument should be Model second should be foreign key and the third one is any other key from Education model. Here, second and third arguments are not mandatory.
In User Model
class User...{
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}
In Education Model
public function user()
{
return $this->belongsTo('App\User');
}
Here, additional parameters are not mandatory might be your addition parameters creates issue,
and now you can retrieve your user with Education by
$user = User::with('education')->get();
This can retrieve all the users with their education.
I hope it helps,Thank you, Happy coding.
Upvotes: 1
Reputation: 28529
Change return $this->hasMany('App\ApplicantEducation','id','user_id');
to return $this->hasMany('App\ApplicantEducation','user_id', 'id');
you also ommit the id
and user_id
.
As your foreign_key is well formed, you can also rwite this simple code,
class User{
public function education()
{
return $this->hasMany('App\ApplicantEducation');
}
}
Class Educations{
public function user()
{
return $this->belongsTo('App\User');
}
}
Upvotes: 1
Reputation: 1213
try this:
in User
Model:
public function educations()
{
return $this->hasMany('App\ApplicantEducation', 'user_id');
}
in Education
Model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
Upvotes: 1