Laravel / Eloquent:是否可以在不设置父代的情况下选择所有子代模型数据?

时间:2019-08-06 13:59:18

标签: laravel eloquent

我有各种父母/子女关系,向下钻研了几个层次。我想知道的是,是否有可能这样做:

$student = Student::find(1);
$student->bursaries()->enrolments()->courses()->where('course','LIKE','%B%');

(最终目标是选择类似于'%B%'的课程),或者我是否必须使用带有联接的DB Query构建器?

模型/关系

学生:

public function bursaries() {
    return $this->hasMany('App\StudentBursary');
}

StudentBursary:

public function enrolments() {
    return $this->hasMany('App\StudentBursaryEnrolment');
}

2 个答案:

答案 0 :(得分:2)

如果要查询的是全部courses 全部enrollments 全部bursaries < / strong>,来自students ,那么,不幸的是,与Has Many Through的关系使您的表太多了,因为它仅支持3个表。

在网上,您会找到可以导入的软件包/或可以遵循的答案,以便为您提供更多解决方案,例如:

1)How to use Laravel's hasManyThrough across 4 tables

2)https://github.com/staudenmeir/eloquent-has-many-deep

无论如何,只有通过Laravel才能实现以下效果:

// Eager loads bursaries, enrolments and courses, but, condition only courses.
$student = Student::with(['bursaries.enrolments.courses' => function($query) {
    $query->where('course','LIKE','%B%');
}])->find(1);

$enrolments = collect();

foreach($student->bursaries as $bursary)  {
    $enrolments = $enrolments->merge($bursary->enrolments);
}

$courses = collect();

foreach ($enrolments as $enrolment) {
    $courses = $courses->merge($enrolment->courses);
}

答案 1 :(得分:1)

当您执行$student->bursaries()而不是$student->bursaries时,它将返回query builder而不是relationship map。因此,要从enrolments()转到bursaries(),您需要做一个bursaries()->get()。看起来应该像这样。

$student->bursaries()->get()[0]->enrolments(),添加了[0],因为我使用get()可以使用first()来避免[0]

$student->bursaries()->first()->enrolments() 但我不确定是否能满足您的要求。