雄辩的关系和多维集合拒绝

时间:2018-11-07 09:07:32

标签: php laravel eloquent

我有一个学校数据库,其中有很多老师,有很多学生,像这样:

class School extends Model
{
    public function teachers()
    {
        return $this->hasMany(Teacher::class,'school_id');
    }
}

class Teacher extends Model
{
    public function students()
    {
        return $this->hasMany(Student::class,'teacher_id');
    }
}

class Student extends Model
{
}

完整查询

$full = School::with(['teachers' => function ($query) {
    $query->with('students');
}])->get();

结果是这样的:

[
    {
        "id": 1,
        "school_name": "First Park",
        "teachers": [
            {
                "id": 1,
                "teacher_name": "Mr.Aha",
                "students": [
                    {
                        "id": 1,
                        "student_name": "Jane",
                        "drop": 1
                    },
                    {
                        "id": 2,
                        "student_name": "Jon",
                        "drop": 0
                    }
                ]
            }
        ]
    }
]

现在,我想删除辍学的学生,并选择教师名,因此我尝试用雄辩和收集来做到这一点,但他们都失败了。

雄辩的方式是:

School::with(['teachers' => function ($teacher) {
    $teacher->with(['students' => function ($student) {
        $student->where('drop', '!=', 0)
    }])->select('teacher_name');
}])->get();

但是结果输出,教师是一个空对象。


收集方式基于完整查询

$full->map(function ($teacher) {
    unset($teacher->id);//there are more column to unset in real life
    $teacher->reject(function ($student) {
        return $student->drop == 0;
    });
});

但是结果与完整查询相同。


我不知道哪种方法更好,更有说服力或更富收藏价值,但它们行不通

2 个答案:

答案 0 :(得分:1)

您还必须选择急需加载的idschool_id列:

School::with(['teachers' => function ($teacher) {
    $teacher->with(['students' => function ($student) {
        $student->where('drop', '!=', 0)
    }])->select('id', 'school_id', 'teacher_name');
}])->get();

然后将其删除,或使用$hidden

$full->map(function ($teacher) {
    unset($teacher->id, $teacher->school_id);
});

答案 1 :(得分:0)

原始文档中的示例。

嵌套的渴望加载 为了渴望加载嵌套关系,可以使用“点”语法。例如,让我们急切地在一项雄辩的陈述中加载本书的所有作者和作者的所有个人联系人:

$ books = App \ Book :: with('author.contacts')-> get();

另外,您可以使用load()方法