【发布时间】:2019-09-20 21:25:02
【问题描述】:
我正在开发一个简单的调查系统,但在获取正确数据时遇到了问题。
我正在尝试检索分配给特定调查的所有包含问题和答案的类别。
ERD:
以下代码几乎可以正常工作,但它不会过滤分配给特定调查的问题。
$categories = Category::whereHas('questions.surveys', function ($query) use ($id) {
$query->where('surveys.id', $id);
})->with('questions', 'questions.answers', 'questions.surveys')
->get();
问题模型:
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');
}
}
类别模型:
class Category extends Model
{
public function questions()
{
return $this->hasMany('App\Models\Surveys\Question');
}
}
调查模型
class Survey extends Model
{
public function questions()
{
return $this->belongsToMany('App\Models\Surveys\Question', 'survey_questions');
}
}
【问题讨论】:
-
您可以记录查询以查看发生了什么吗? stackoverflow.com/questions/41140975/…
-
我建议您安装 Laravel 调试工具栏 (github.com/barryvdh/laravel-debugbar),因为它会显示运行的 RAW sql 查询。这很可能可以帮助您缩小问题的范围。但是,我认为问题与 whereHas('questions.surveys') 有关。如果我没记错的话,这个参数应该是一个模型函数。所以应该是“问题”,然后你把 where 放在 $query->surveys()->where('surveys.id', $id);