约束预加载关系和嵌套关系-Laravel 8
我有一张桌子。每个章节可能有多个注释,每个注释不是由用户创建的 表格结构 用户=>id |名称 章节=>id |标题 备注=>id |章节id |用户id 关系约束预加载关系和嵌套关系-Laravel 8,laravel,eager-loading,Laravel,Eager Loading,我有一张桌子。每个章节可能有多个注释,每个注释不是由用户创建的 表格结构 用户=>id |名称 章节=>id |标题 备注=>id |章节id |用户id 关系 //Chapter Model public function notes() { return $this->hasMany(Note::class, 'chapter_id', 'id'); } //Note Model public function user() { return $this->b
//Chapter Model
public function notes()
{
return $this->hasMany(Note::class, 'chapter_id', 'id');
}
//Note Model
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
现在,我正在尝试获取所有章节及其注释以及创建注释的用户
Chapter::with([
'notes' => function($q) {
$q->select('id','chapter_id','note','noted_at');
},
'notes.user' => function($q) {
$q->select('id','first_name','last_name');
},
]);
我正在获取notes关系,但每个notes中的用户关系都是null
Chapter::with('notes.user')->get();
我也试着跟随,但没有运气
Chapter::with([
'notes' => function($q) {
$q->select('id','chapter_id','note','noted_at');
$q->with('user:id,first_name,last_name');
},
]);
我的输出应该类似于下面的json
{
"id":2,
"title":"Sed.",
"notes":[
{
"id":82,
"chapter_id":2,
"note":"Dicta ipsam illum possimus qui non. Nihil sed ipsum et rem reprehenderit omnis aspernatur. Ut velit quo incidunt quaerat reiciendis.",
"noted_at":383,
"user":{
"id":1,
"first_name":"Fahad",
"last_name":"Shaikh"
}
}
]
}
简单地说,我如何在约束
注释
和用户
关系的同时加载嵌套关系用户
Chapter::with('notes.user')->get();
使用“选择零件”:
Chapter::with('notes', function($noteQueryBuilder) {
$noteQueryBuilder->select('id','chapter_id','note','noted_at', 'user_id')
->with('user', function($userQueryBuilder) {
$userQueryBuilder->select('id','first_name','last_name');
});
})->get();
如果要限制便笺上的选择,则需要包含
user\u id
,因为它将用于为便笺加载用户。您可以在每个实体的查询生成器上链接其他条件。是的,但我的目标是约束注释
和用户
关系,同时急切地加载两者them@FahadShaikh他们两个都会很兴奋,这里有什么问题?“约束”是指对这些关系设置条件或添加语句@FahadShaikh将有问题的条件添加到您原来的帖子中。如果您谈论的是select
部分,那么您最好使用这些方法