【发布时间】:2017-09-08 12:41:46
【问题描述】:
我有三个实体表,student、course 和 semester。它们通过三元数据透视表链接在一起——也就是说,每一行代表“学生 X 在 Z 学期学习课程 Y”:
# Table course_students
| student_id | semester_id | course_id |
|------------|-------------|-----------|
| 18 | 4 | 80 |
| 18 | 8 | 64 |
| 18 | 8 | 60 |
据此,我想构建一个嵌套集合:
- 每个学生都有一个集合,其中包含该学生至少修过一门课程的学期;
- 给定学生的每个学期都有一个集合,其中包含该学生在该学期学习的课程。
因此,对于上表,我想调用类似 Student::find(18)->with('coursesBySemester') 的名称并获得如下所示的集合:
{
"id": 18,
"first_name": "Wesley",
"last_name": "Snipes",
"email": "wes@expendables.com",
"semesters": [
{
"id": 4,
"name": "Fall 2014",
"pivot": {
"student_id": 18,
"semester_id": 4
},
"courses": [
{
"id": 80,
"title": "Game Theory",
"pivot": {
"semester_id": 4,
"course_id": 80,
"student_id": 18
}
},
]
},
{
"id": 8,
"name": "Fall 2016",
"pivot": {
"student_id": 18,
"semester_id": 8
},
"courses": [
{
"id": 64,
"title": "Introduction to Calculus with Applications",
"pivot": {
"semester_id": 8,
"course_id": 64,
"student_id": 18
}
},
{
"id": 60,
"title": "Introduction to Finite Math 1",
"pivot": {
"semester_id": 8,
"course_id": 60,
"student_id": 18
}
}
]
}
]
}
我尝试过的
通过我的Student 模型中定义的以下关系,我可以实现大部分目标:
/**
* Load a collection of semesters during which this student was enrolled in at least one course, and the courses that they took in each semester
*/
public function coursesBySemester()
{
return $this->belongsToMany('UserFrosting\Sprinkle\Btoms\Model\Semester', 'course_students')
->with(['courses' => function ($query) {
return $query->where('course_students.student_id', $this->id);
}])
->groupBy('semester_id');
}
Semester 模型定义了以下关系:
/**
* Lazily load a collection of courses that were taken in this semester.
*/
public function courses()
{
return $this->belongsToMany('UserFrosting\Sprinkle\Btoms\Model\Course', 'course_students')->withPivot('student_id');
}
问题是,当我在我的 coursesBySemester 关系中调用 with('courses') 时,它会检索 所有 学生在该学期学习的所有课程。我只想要家长学生在那个学期学习的课程。
如您所见,我试图通过使用where('course_students.student_id', $this->id) 来约束这种关系,但$this->id 实际上并没有在关系的上下文中设置任何值。我也尝试过wherePivot 方法,但同样,我不知道如何根据父Student 模型的id 动态设置该约束。
我意识到我可以创建一个手动遍历并构建我想要的集合的助手,但我真的很想将它作为一个单一的关系来实现,以便我可以在其他查询构建器表达式中流畅地使用它。
【问题讨论】:
标签: php laravel eloquent many-to-many relationship