staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

withIntermediate eager loading relationships #44

Closed NeoKactus closed 5 years ago

NeoKactus commented 5 years ago

The filtering is working as expected but, is there any way to eager load relationships for a intermediate/pivot table?

public function teachers()
{
       return $this->hasManyDeepFromRelations($this->enrolments(), (new Enrolment())->user())
                    ->withIntermediate(Enrolment::class)
                    ->where('request_status', 'Approved') //Filter by Enrolment column
                    ->with('school')               //Enrolment model relationship (Doesn't work)
                    ->with('enrolment.school')     //I have also tried this (Doesn't work)
                    ->with('courses')           //User model relationship (Works)
                    ->whereHas('roles', function ($query) { //Filter by user.roles column
                        $query->where('name', 'teacher');
                    });
}

I tried this as well but I see that hasManyDeepFromRelations doesn't preserve additional constraints. https://github.com/staudenmeir/eloquent-has-many-deep/issues/36#issuecomment-519950021

public function enrolments()
{
        return $this->hasManyThrough(
            Enrolment::class,
            CourseSchool::class,
            'course_id',
            'course_school_id'
        )
                    ->with('school'); //Also doesn't work

}
staudenmeir commented 5 years ago

How are you using the teachers relationship?

NeoKactus commented 5 years ago

The goal was to be able to send a query like this to my API. /api/courses?include=teachers,students&filter[fullname]=Chemistry%209 Query builder to resolve the includes to relationships.

Course ( Contains teachers() ) CourseSchool -> School (This is the relationship I want to eager load)
Enrolment User

Roles

staudenmeir commented 5 years ago

It's only possible with lazy eager loading:

$courses = Course::with('teachers')->get();

$teachers = $courses->pluck('teachers')->flatten();

$teachers->load('enrolment.school');
NeoKactus commented 5 years ago

I will give it a shot. Thank you for the insight.