代表特定 id 在 table 中插入数据

Insert data in table behlf of prticuler id

我正在尝试通过 Id 将数据插入数据库。我 有三个问题,我有这些问题的答案。题 id 已正确插入 table。但是这些问题的答案Id 未正确插入。只插入一个问题答案 table。让我解释一下功能:

$post['SurveyAnswer']['question_id'] 有三个值。如果我们 print_r( $post['SurveyAnswer']['question_id']) 那么结果是

Array
(
    [0] => 833
    [1] => 834
    [2] => 835
)

现在我有了这个问题的答案。 print_r($post['SurveyAnswer']['answer']); 的输出 是。

Array
(
    [0] => text123
    [1] => hello
    [2] => hello
)

我想做的是将特定问题的答案保存在数据库中。 我需要这样的结果。

   [833] => text123
   [834] => hello
   [835] => hello

这是我的函数

public function actionSaveAnswer()
{
    $post = \Yii::$app->request->post();
    // echo "<pre>";print_r($post);die();
    foreach ($post['SurveyAnswer']['question_id'] as $ques) {
        $post['SurveyAnswer']['answer'];
        $surveyAnswer = new SurveyAnswer();
        $surveyAnswer->question_id = $ques;

    }
    if ($surveyAnswer->save()) {
        $flag = true;
        \Yii::$app->session->setFlash('success', \Yii::t('app', 'Your answers saved successfully.'));
    }
}

我没看到你在哪里添加答案。如果您的答案和问题 ID 与您指出的一致,请尝试这样的操作:

foreach ($post['SurveyAnswer']['question_id'] as $id => $ques) {
    $surveyAnswer = new SurveyAnswer();
    $surveyAnswer->question_id = $ques;
    $surveyAnswer->answer = $post['SurveyAnswer']['answer'][$id];
    $surveyAnswer->save();
}

而且你应该在循环中保存一个答案。否则只会保存一行。