Is this a situation that can be done?
Using HasManyDeep with Model and WithCount
I enlisted the HasManyDeep package written by Jonas Staudenmeir located here: https://github.com/staudenmeir/eloquent-has-many-deep.I'm retrieving all courses that were taken during a semester. As you can see there is not a has many relationship between semester and course. Instead, I'm using the many-to-many relationship between a semester and a course section, and with the course sections get the one-to-many relationship between the course section and course.
Currently I'm getting the collection of courses for a semester. What I also need to do is get the count of students that have participated in the sections for these courses for the specific semester.
What can add onto my current query so that I can add a total of a nested relationship.
Semester
- id
- name
...
Course
- id
- name
...
CourseSection
- id
- course_id
...
CourseSectionSemester
- id
- course_section_id
- semester_Id
...
CourseSectionSemesterStudent
- id
- course_section_semester_id
- student_id
Semester.php
public function courses()
{
return $this->hasManyDeep(
Course::class,
[CourseSectionSemester::class, CourseSection::class],
['semester_id', 'course_id', 'id']
);
}
Query
$query = $this->semester->courses()->newQuery()
->whereHas('sections.semesters', function ($query) {
$query->withCount('students');
})
Please or to participate in this conversation.