DEV Community

Victor Basumatary
Victor Basumatary

Posted on

Laravel Relationship Gotcha

Laravel is nice. It lets you define relationships painlessly.

// app/MultipleChoiceQuestion.php
class MultipleChoiceQuestion extends Model
{
    public function answers()
    {
        return $this->hasMany(\App\Answer::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

We can even make relationships in the other direction.

// app/Answer.php
class Answer extends Model
{
    public function question()
    {
        return $this->belongsTo(\App\MultipleChoiceQuestion::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

If we know we're often going to query for the answers to our questions when we query for the questions, it makes sense to eager load them by default.

// app/MultipleChoiceQuestion.php
class MultipleChoiceQuestion extends Model
{
    protected $with = ['answers'];

    public function answers()
    {
        return $this->hasMany(\App\Answer::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

But what happens when we eager load the question on the answer as well?

// app/Answer.php
class Answer extends Model
{
    protected $with = ['question'];

    public function question()
    {
        return $this->belongsTo(\App\MultipleChoiceQuestion::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

Chaos. When you query the question you query for its answers as well which in turn queries for the question they belongs to and...

Your relationships must terminate somewhere.

Top comments (0)