我正在做问答形式。我有 2 张桌子
questions
桌子和 choices
桌子。我完美地将问题数据和选择数据保存到他们的表中,除了选择表中的question_id
。我想将问题 ID 保存到选择表字段名称 question_id
。
问题表
| id | question |
| 1 | data1 |
| 2 | data2 |
选择表
| id | question_id | choices |
| 1 | | data1 |
| 2 | | data2 |
下面是我的控制器
$questions = $request->question;
foreach($questions as $question => $question_value) {
$questionsS[] = Question::create([
'question' => $request->question[$question],
]);
}
$choices = $request->choices;
foreach ($choices as $choice => $choice_value) {
$choicesS[] = Choice::create([
'question_id' => $question->id,
'choice' => $choice_value,
]);
}
我遇到错误“尝试读取 int 上的属性“id””,突出显示“question_id”=> $question->id,
希望有人帮忙。
简单来说,
我不知道你的目标,但如果我修复它,你的代码应该是这样的:
$questions = $request->question;
// may be ['question one ?', 'question two ?' ...]
$choices = $request->choices;
// may be ['choose A', 'choose B' ...]
// $questions array and $choices array must be same length
// i think in your case it will be same length, right ?
foreach($questions as $questionIndex => $question) {
$currentQuestion = Question::create([
'question' => $question,
]);
$questionsS[] = $currentQuestion;
$choicesS[] = Choice::create([
'question_id' => $currentQuestion->id,
'choice' => $choices[$questionIndex],
]);
}
循环中的$currentQuestion将是一个从数组元素创建的对象,您可以从中获取id来创建一个新的Choice对象。