lundi 7 août 2017

Nesting hasMany() relationships in Laravel

So I have a CourseTerm model and CourseAttendee model and I would like to get in one relationship the attendees of the courses that overlap in time and have the same lecturer. Here is the relevant code:

class CourseTerm extends PEloquent
{
    public function directAttendees()
    {
        return $this->hasMany('CourseAttendee');
    }

    public function overlappingCourseTerms()
    {
        return $this->lecturer->givenCourseTerms() // a hasMany relationship that returns CourseTerms
                    ->where('course_start', '<=', $this->course_start)
                    ->where('course_end', '>=', $this->course_end);
    }
}

Now I would like to get the attendees that participate in all the related courses as a hasMany relationship, something like this:

public function totalAttendees()
{
     return $this->overlappingCourseTerms->directAttendees();
}

But this, of course does not work because the collection returned by overlappingCourseTerms does not have the attendees() method. The hasManyThrough() method of Eloquent models allows as parameters only the classes of the models, not relationships (like the overlappingCourseTerms() one), so I wasn't able to use it as well.

Do you have any suggestion on how to achieve the desired behavior?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire