laravel - laravel eloquent 'has' 方法的行为出人意料
问题描述
如果 Section 模型至少有一个,我想获得它的集合User
。从文档中,该has()
方法可以做到这一点,太好了。检索到的集合中没有users
关系。然而,当我遍历集合时,我可以获得users
. 为什么?
class Section extends Model
{
protected $guarded = [];
public function users()
{
return $this->hasMany('App\User');
}
}
class User extends Authenticatable
{
protected $guarded = [];
public function section()
{
return $this->belongsTo('App\Section');
}
}
我所做的是:
$section = Section::where('id' , 1)->has('users')->get();
集合是这样的:
Illuminate\Database\Eloquent\Collection {#3025
all: [
App\Section {#3015
id: 1,
class_id: 1,
section_name: "A",
created_at: "2019-12-14 18:26:01",
updated_at: "2019-12-14 18:26:01",
},
],
}
现在奇怪的是,当我执行以下操作时,即使在集合users
中不存在关系,它也会给出用户的属性。
为什么?
@foreach ($section as $section)
@foreach ($section->users as $student)
<p>{{$student->name}}</p>
@endforeach
@endforeach
solomon
uche
kene
解决方案
好的,现在我明白你的问题了。
- 第一的
该has
方法并不意味着它将包含User
. 这意味着这将返回所有sections
至少有一个用户的人。我认为有/有Section
id ===1 的用户。因此,无论有没有它,在您的代码has
中都没有任何区别。
如果要显式加载关系,则应使用with
Section::where('id' , 1)->with('users')->get();
. 然后你应该在每个部分下收集用户。
第二
您仍然可以访问
blade
文件中的用户属性的原因是lazy loading
. 即使它不包含在原始数据库查询和结果中,但是当您尝试访问它时,laravel 仍然会尝试为您获取它们。这可能会导致 N+1 问题。
推荐阅读
- cors - 调试时禁用标头中的附加字段“X-DevTools-Request-Id”(电子/axios)
- angular - Angular 5+ 中的服务遗产
- python-3.x - Python3,使用openpyxl读取单元格
- javascript - 列表上的自动换行
- java - 与远程mysql的jdbc连接
- node.js - 天蓝色中的错误“找不到设置属性的活动上下文”
- javascript - 在网站引导程序上更改容器的背景颜色
- javascript - Javascript - 在 if 中添加事件监听器
- path - 如何告诉 Robot Framework 规范化路径中的转义空间?
- html - 加载大量图像并将前 100 个设置为可见