我有这些表“问题”、“参与者”、“选择”和“choice_participant(数据透视表)”。我设法在用户页面中显示他们的选择问题(我使用单选框来选择选项)并保存到表“choice_participant”。
“参与者”样本表
id | 名字 |
---|---|
1 | 约翰·多伊 |
2 | 菲利普·克鲁兹 |
3 | 玛丽·安妮 |
“问题”示例表
id | 问题 | 问题类型 |
---|---|---|
1 | 问题#01 | 单选 |
2 | 问题#02 | 多重选择 |
3 | 问题#03 | 单选 |
“选择”示例表
id | 问题_id | 选择 |
---|---|---|
1 | 1 | 选择01 |
2 | 1 | 选择02 |
3 | 1 | 选择03 |
4 | 2 | 选择04 |
5 | 2 | 选择05 |
6 | 2 | 选择06 |
“choice_participant(数据透视表)”的示例表
id | 参与者_id | 选择_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 4 |
刀片展示
`@if($question->question_type == 'single_select') @foreach($question->choices as $choice) id}}]" type="radio" value="{{$choice->id}}" name="choices[{{$question->id}}]"> id}}]">{{ $choice->choice }} @endforeach
@其他 @foreach($question->choices as $choice) id}}]" type="checkbox" value="{{$choice->id}}" name="choices[{{$question->id}}]"> id}}]">{{ $choice->choice }} @endforeach @万一 `
保存到枢轴的控制器
foreach ($request->choices as $key => $choice_value) { $choices = $participant->choices()->attach($choice_value); }
如果问题类型为“single_select”,则可以完美保存,但在“multiple_select”中,它仅保存 1 个选择。我需要将所有选定的选项保存在数据透视表的复选框中。
希望各位专家的帮助。
谢谢!
我希望保存用户在“single_select(单选按钮)”中选择的所有选项以及“multiple_select(复选框)”中的所有选定选项
在附加选项之前将其展平。这将正确处理单个和多个选项并将所有选定的选项附加给参与者。
foreach ($request->choices as $choices) {
if (is_array($choices)) {
foreach ($choices as $choice) {
$participant->choices()->attach($choice);
}
} else {
$participant->choices()->attach($choices);
}
}