简体   繁体   English

Laravel 获得学校用户

[英]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用户表有 school_id

I made this relationship:我建立了这样的关系:

User.php用户.php

public function school(){
    return $this->belongsTo('App\Models\School');
}

School.php学校.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?我从学校 model 得到每个领域,但用户不在那里,我如何让用户也出现在那里而不必做?

dd($school->user)

Nvm I fixed it by doing this query Nvm 我通过执行此查询修复了它

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

You should use the Eloquent feature called Eager Loading您应该使用名为Eager Loading的 Eloquent 功能

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:或者,如果您愿意自动加载用户而不必每次都指定 with('user'),您可以在 School model 中设置 $with 属性,如下所示:

protected $with = ['user'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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