[英]Eloquent model's relations
我正在开发一个简单的调查系统,但在获取正确数据方面遇到了问题。
我正在尝试检索分配给特定调查的所有带有问题和答案的类别。
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');
}
}
为此,您还需要限制您的急切负载:
$categories = Category::with([
'questions' => function ($query) use ($id) {
$query->with('answers', 'surveys')
->whereHas('surveys', function ($query) use ($id) {
$query->where('id', $id);
});
},
])->whereHas('questions.surveys', function ($query) use ($id) {
$query->where('id', $id);
})->get();
通过这种方式,您只能获得与特定调查相关的类别,并且仅获得与该类别和特定调查相关的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.