Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

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');
        })
0 likes
2 replies
jrdavidson's avatar

I was suggested to realign some of my database tables and this is what I have now. The problem I have with this is because for each semester has an attached course and has a section but I need a way to show what course is attached to the course section.

Any suggestions?

Semester
- id
- name
...

Course
- id
- name
...

CourseSection
- id
- day
- teacher
- start_time
- end_time
...

CourseSemester
- id
- course_section_id
- semester_Id
- course_id
...

CourseSemesterStudent
- id
- course_section_semester_id
- student_id

Please or to participate in this conversation.