R
R
Ruslan Tilyaev2020-05-27 14:07:45
Yii
Ruslan Tilyaev, 2020-05-27 14:07:45

How to write to database multiple times?

Hello, I need to save 2 records to a database table at the same time. But I only have 1 last one, tell me. Thank you in advance.

_form.php

<div class="row">
        <div class="col-md-2">
                <span>
                        Вариант №1
                </span>
        </div>
        <div class="col-md-10">
            <?= $form->field($answers, 'answer[]')->textarea(['rows' => 6]) ?>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
                <span>
                        Вариант №2
                </span>
        </div>
        <div class="col-md-10">
            <?= $form->field($answers, 'answer[]')->textarea(['rows' => 6]) ?>
            <br>
        </div>
    </div>


controller
public function actionCreate()
    {
        $answers = new Answer();

        if ($model->load($answers->load(Yii::$app->request->post())) {

            foreach ($answers->answer as $value) {
                $answers->question_id = 1;
                $answers->answer = $value;
                $answers->save();
//                debug($answers->getErrors());
            }
        }

        return $this->render('create', [
            'answers' => $answers,
        ]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Tilyaev, 2020-05-27
@Heckfy325

Yii::$app->db->createCommand()->batchInsert('answer', ['answer', 'question_id'], [
                    [$value, 1],
                ])->execute();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question