我应该如何使用Laravel Eloquent查询并使用关系?(How should I use Laravel Eloquent queries and use relationships?)

编程入门 行业动态 更新时间:2024-10-23 21:40:48
我应该如何使用Laravel Eloquent查询并使用关系?(How should I use Laravel Eloquent queries and use relationships?)

我有一个属于DepartmentUser模型。

所以部门有id名字字段。

在用户模型我得到:

public function department() { return $this->belongsTo('Department'); }

这样我可以做类似的事情: Auth::user()->department->name获取部门用户所属的实际名称。

但是,当我调用某些用户时,我无法找到获取包含其department属性的多行的最佳方法。

我写:

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

有一个更好的方法吗?

I have a User model which belongsTo a Department.

So Department got id and name fields.

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.

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?

最满意答案

您可以急切加载相关模型,以便只为一个数据库查询加载所有用户,并将包含在JSON输出中:

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

更多关于Laravel Docs中的热切加载

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:

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

More about eager loading in the Laravel Docs

更多推荐

本文发布于:2023-07-25 10:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   关系   Laravel   Eloquent   queries

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!