staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

belongsTo > belongsTomany #62

Closed jvbalcita closed 3 years ago

jvbalcita commented 3 years ago

Hi,

I don't know if I'm just making things complicated but I can't make this work.

I have a Course, Student and Teachers.

Student belongsTo > Course > belongsToMany > Teachers

And from student model I wanted to get directly the teachers

public function teachers()
    {
        return $this->belongsToThrough(Teacher::class, [Course::class, 'teacher_has_courses']);
    }

Thanks in advance.

staudenmeir commented 3 years ago

BelongsToThrough relationships only return a single related model (i.e. one teacher).

You need to use a different package: https://github.com/staudenmeir/eloquent-has-many-deep

class Student extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function teachers()
    {
        return $this->hasManyDeep(
            Teacher::class,
            [Course::class, 'teacher_has_courses'],
            ['id'],
            ['course_id']
        );
    }
}
jvbalcita commented 3 years ago

You are awesome @staudenmeir. You always save the day! :) Thank you!