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);
}
}
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);
}
}
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);
}
}
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);
}
}
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)