简体   繁体   中英

Laravel get school users

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)

Nvm I fixed it by doing this query

        $schools = School::with('user')->get();

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'];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM