简体   繁体   English

我应该如何使用Laravel雄辩的查询和使用关系?

[英]How should I use Laravel Eloquent queries and use relationships?

I have a User model which belongsTo a Department . 我有一个User ,其模型belongsTo一个Department

So Department got id and name fields. 因此,部门获得了ID名称字段。

At the User model I got: 在用户模型中,我得到了:

public function department() {

      return $this->belongsTo('Department');
}

That way I can do something like: Auth::user()->department->name getting the actual name of the department user belongs to. 这样,我可以执行以下操作: Auth::user()->department->name获取部门用户所属的实际名称。

However, when I'm calling some users, I can't figure out best way to get multiple rows containing its department attribute with a name. 但是,当我打电话给某些用户时,我想不出获取包含其部门属性和名称的多行的最佳方法。

I wrote: 我写:

$users = User::all();
foreach ($users as $user) {
    $user -> department = Department::find($user->department_id)->name;
}

Is there a better way to do this? 有一个更好的方法吗?

You can eager load related models so they are loaded for all users with only one database query and will be included in JSON output: 您可以急于加载相关模型,以便仅通过一个数据库查询即可为所有用户加载它们,并将其包含在JSON输出中:

$users = User::with('department')->get();

More about eager loading in the Laravel Docs 有关在Laravel文档中渴望加载的更多信息

It seems that you got the relationship between User Model and Department Model already. 看来您已经有了用户模型和部门模型之间的关系。 So you can call it like you did with Auth(). 因此,您可以像使用Auth()一样调用它。

$users = User::all();
foreach ($users as $user) {
    echo $user->department->name ;
}

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

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