我有一个属于Department的User模型。
所以部门有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
更多推荐
发布评论