moonwalker
moonwalker

Reputation: 1177

Laravel Eloquent Eager Loading Multiple Has Many Relationship

In my DB the model Class has many Student and every Student has many Homework and every Homework has many Question. How can I write a single query with eager loading to get every Question that is related to one specific Class?

I can get a nested structure with this code:

$class = Class::find($classId);
$collection = $class->with('students.homeworks.questions')->get();

How can I get the array of all questions in this collection? What I get currently with toArray() method is a structure like this:

{ //Class
    ...
    students: [
        {
            homeworks: [
                {
                    questions: [{...}]
                },
                ...
            ]
        },
        ...
    ]
}

Upvotes: 1

Views: 603

Answers (2)

Abel
Abel

Reputation: 53

You could create a function within the Students model:

public function questions(){
   $questions = [];
   foreach($this->homework as $homework){
        foreach($homework->questions as $question){
           array_push($questions, $question);
        }
   }
   return $questions;
}

This way every time you have an student object you can get an array of all the questions like this:

$student->questions

Hope this could help you.

Upvotes: 1

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

There is no native relationship for this case.

I created a HasManyThrough relationship with unlimited levels: Repository on GitHub

After the installation, you can use it like this:

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

    public function questions() {
        return $this->hasManyDeep(Question::class, [Student::class, Homework::class]);
    }
}

Upvotes: 1

Related Questions