I'm developing a simple survey system, and I'm having problem with getting the right data.
I'm trying to retrieve all categories with questions and answers, that are assigned to a specific survey.
ERD:
The following code nearly works, however it does not filter the questions that are assigned to a specific survey.
$categories = Category::whereHas('questions.surveys', function ($query) use ($id) {
$query->where('surveys.id', $id);
})->with('questions', 'questions.answers', 'questions.surveys')
->get();
Question Model:
class Question extends Model
{
public function answers()
{
return $this->belongsToMany('App\Models\Surveys\Answer', 'question_answers');
}
public function category()
{
return $this->belongsTo('App\Models\Surveys\Category');
}
public function surveys()
{
return $this->belongsToMany('App\Models\Surveys\Survey', 'survey_questions');
}
}
Category Model:
class Category extends Model
{
public function questions()
{
return $this->hasMany('App\Models\Surveys\Question');
}
}
Survey Model
class Survey extends Model
{
public function questions()
{
return $this->belongsToMany('App\Models\Surveys\Question', 'survey_questions');
}
}