I am making a project that will have schools that are already seeded into the database, one user has one school.
User table has school_id
I made this relationship:
User.php
public function school(){
return $this->belongsTo('App\Models\School');
}
School.php
public function user()
{
return $this->hasMany('App\Models\User', 'school_id');
}
When i do
$school = School::where('id', 1)->first();
dd($school);
I get every field from the school model but the users aren't there,how do i make that the users appear there too without having to do?
dd($school->user)
CodePudding user response:
Nvm I fixed it by doing this query
$schools = School::with('user')->get();
CodePudding user response:
You should use the Eloquent feature called Eager Loading
So, to eager load all the users, you should do:
School::with('user')->get();
Alternatively, if you are willing to automatically load the user without having to specify with(‘user’) every time, you can set the $with property in your School model like this:
protected $with = [‘user’];