约束急切加载关系以及嵌套关系 - Laravel 8

时间:2021-03-02 17:22:04

标签: laravel eager-loading

我有章节表。每个章节可能有多个注释,每个注释都是由用户创建的。

表格结构

用户 => id |姓名

章节 => id |标题

注释 => id |章节编号 |用户 ID

关系

library(dplyr)
df1 <- df1 %>%
  mutate(site_no = ifelse(row_number()<=15, paste0("0", site_no), site_no)) # returns the leading zero but makes class character

现在我正在尝试获取所有章节及其注释以及创建注释的用户。

//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'); }, ]);

我也尝试过,但没有成功

null

我的输出应该类似于以下 json

Chapter::with([
    'notes' => function($q) {
            $q->select('id','chapter_id','note','noted_at');
            $q->with('user:id,first_name,last_name');
        },
]);

简单地说,我如何在限制 { "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" } } ] } user 关系的同时急切加载嵌套关系 notes

1 个答案:

答案 0 :(得分:0)

试试下面的这段代码,你会得到每个笔记中用户的笔记

const obj1 = { age: 25, color: "white", weight: true };
const obj2 =  { color: "white", weight: true }
const obj3 = { age: 26, color: "white", weight: true }

console.log(matches(obj1, obj2)); // true
console.log(matches(obj2, obj1)); // false
console.log(matches(obj3, obj1)); // false
console.log(matches(obj3, obj2)); // true

使用选择部分:

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(); 因为它会被用来急切地加载用户的笔记。您可以在每个实体的查询构建器上链接其他条件。