【发布时间】:2018-08-20 20:47:56
【问题描述】:
如果用户在会议中进行注册并且注册表会收集此数据:
"name" => array:1 [▼
1 => array:2 [▼
1 => "Jake" // name of the participant being registered in the registration_type_id 1
2 => "John" // name of the participant being registered in the registration_type_id 1
]
]
"surname" => array:1 [▼
1 => array:2 [▼
1 => "W" // surname off 1st participant being registered in the registration_type_id 1
2 => "K" // surname off 2nd participant being registered in the registration_type_id 1
]
]
"answer" => array:1 [▼
1 => array:2 [▼
1 => array:2 [▼ // answers of the 1st participant being registered in the registration_type_id 1
1 => "answer1p1"
2 => "answer2p1"
]
2 => array:2 [▼ // answers of 2nd participant being registered in the registration_type_id 1
1 => "answer1p2"
2 => "answer2p2"
]
]
]
然后有必要将参与者信息存储在参与者表中,并将与每个参与者关联的答案存储在答案表中。在参与者表中插入工作正常。
问题:在答案表中插入无法正常工作。在数据库中,它应该存储为:
id | participant_id | question_id | answer
159 | 153 | 1 | answer1p1
161 | 153 | 2 | answer2p1
163 | 154 | 1 | answer1p2
165 | 154 | 2 | answer2p2
但是是这样存储的:
id | participant_id | question_id | answer
159 | 153 | 1 | answer1p1
161 | 153 | 1 | answer1p2
163 | 154 | 1 | answer1p1
165 | 154 | 1 | answer1p2
160 | 153 | 2 | answer2p1
162 | 153 | 2 | answer2p2
164 | 154 | 2 | answer2p1
166 | 154 | 2 | answer2p2
要在参与者和答案表中插入的代码:
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
$participant_result = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
if (isset($request['answer'][$key])) {
foreach ($request->all()['answer'][$key] as $rID => $answers) {
foreach ($answers as $question_id => $answer) {
$answer = Answer::create([
'question_id' => $question_id,
'participant_id' => $participant_result->id,
'answer' => $answer,
]);
}
}
}
}
}
【问题讨论】: