【发布时间】:2017-08-24 07:17:43
【问题描述】:
我有 3 个表,分别是 polls、poll_questions 和 poll_choices。它们的关系是 polls 有很多 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 和 poll_question。但是当我尝试添加投票选项时,它给出了一个错误。我无法访问 poll_questions 的 poll_choices 方法。
我该如何解决这个问题?
Laravel 5.4
完整的错误日志:
BadMethodCallException 调用未定义的方法 Illuminate\Database\Query\Builder::poll_choices()
【问题讨论】: