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

doubleprincez's avatar

BelongsToThrough for deep fetching

I have some relationships e.g Department, Level, Course Department belongsToMany Level belongsToMany Course now I'm trying to fetch departments offering a course using this relationship I tried using \Staudenmeir\EloquentHasManyDeep but it keeps returning

 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'levels.course_id' in 'field list' (SQL: select `departments`.*, `levels`.`course_id` as `laravel_through_key` from `departments` inner join `levels` on `levels`.`id` = `departments`.`level_id` where `levels`.`course_id` = 1 and `departments`.`deleted_at` is null and `levels`.`deleted_at` is null)

Course Model

 public function levels()
    {
        return $this->belongsToMany(Level::class, LevelCourse::class);
    }

   public function departments()
    {
        return $this->hasManyThrough(Department::class, Level::class);
    }

Level Model

  public function courses()
    {
        return $this->belongsToMany(Course::class, LevelCourse::class)->withPivot('code');
    }

    public function departments()
    {
        return $this->belongsToMany(Department::class, DepartmentLevel::class);
    }

This is the code I used in testing

    dd(Course::first()->departments);
0 likes
3 replies
doubleprincez's avatar

Please, anyone.... It's just a simple request.... I need to fetch the next relationship of two belongsToMany relationships:

department  -> (department_levels)-> levels ->(course_levels)-> courses

I can fetch the department levels, from levels I can fetch courses, from courses I can fetch levels and from levels I can fetch departments and courses, but just fetching courses from department in a belongsToMany relationship is still not clear to me.

doubleprincez's avatar

I'm currently fetching the courses this way but I don't think it is an efficient way

 $department_id = (int)$this->sanitize(request()->get('department_id'));
            $departments = app()->make(DepartmentInterface::class)->findTheFirstOne('id', $department_id, ['levels', 'levels.courses']);
            return collect($departments->levels->map(function ($dep) {
                return $dep->courses;
            }))->flatten(1)->unique();

Please or to participate in this conversation.