我有3个表,分别是民意调查,poll_questions和poll_choices。他们的关系是民意调查有很多poll_questions和poll_questions有很多poll_choices。我想插入但是我收到了poll_choices()的错误BadMethodCallException。
民意调查模式:
public function poll_questions() {
return $this->hasMany(PollQuestion::class);
}
民意调查问题模型:
public function polls() {
return $this->belongsTo(Poll::class, 'poll_id');
}
public function poll_choices() {
return $this->hasMany(PollChoice::class);
}
民意调查选择模型:
public function poll_questions() {
return $this->belongsTo(PollQuestion::class, 'poll_question_id');
}
这是我的控制器:
public function store(Request $request) {
$rules = [
'title' => 'required',
'questions' => 'required|poll_questions',
];
$this->validate($request, $rules);
$newPoll = Poll::create(request()->all());
$questions = $request->input('questions');
for ($i = 0; $i < count($questions); $i++) {
$poll_question = new PollQuestion();
$poll_question->input_type = $questions[$i]["input_type"];
$poll_question->question = $questions[$i]["question"];
$newPoll->poll_questions()->save($poll_question);
if ($questions[$i]["input_type"] === '0') {
for ($j = 0; $j < count($questions[$i]["choices"]); $j++) {
$poll_choices = new PollChoice();
$poll_choices->choice = $questions[$i]["choices"][$j];
$newPoll->poll_questions()->poll_choices()->save($poll_choices);
}
}
}
return $this->showOne($newPoll);
}
我在此行中收到错误:$newPoll->poll_questions()->poll_choices()->save($poll_choices);
另外,我试过:$newPoll->poll_questions->poll_choices()->save($poll_choices);
我可以添加民意调查和poll_question完美。但是当我尝试添加轮询选择时,它会出错。我无法访问poll_questions的poll_choices方法。
我该如何解决这个问题?
Laravel 5.4
完整错误日志:
BadMethodCallException调用未定义的方法 照亮\数据库\查询\生成器:: poll_choices()
答案 0 :(得分:1)
当您执行此操作时,您已保存投票问题并将其与投票相关联:
$newPoll->poll_questions()->save($poll_question);
所以剩下的就是保存问题的选择,你不需要再涉及父民意调查了。所以在你的问题循环中,使用它代替你拥有的东西:
$poll_question->poll_choices()->save($poll_choices);