0

I want to insert many record to database in one action.

In this controller I used foreach for insert to database, but just the last record inserts to database, I don't know why. I want to insert all the record to database.

My controller:

              if (isset($_POST['month'])) {
                    $name = $_POST['month'];
                    $price = $_POST['Request'];
                    $i = 0;
                    foreach ($name as $month) {
                        $model->month = $month;
                        $model->price = $price['price'];
                        $model->save(false);
                        $i++;
                    }
                        $pay_info = [
                            'cost' => $price['price'],
                            'title' => 'title'];
                        return $this->render('payment', ['pay_info' => $pay_info]);
                }

1 Answer 1

1

A simple way is based on the fact you should create a new model in you foreach for each instance you want save (your controller code is not complete so i can't know your model )

             if (isset($_POST['month'])) {
                $name = $_POST['month'];
                $price = $_POST['Request'];
                $i = 0;
                foreach ($name as $month) {
                    $model =  new YourModel(); /*   here */
                    $model->month = $month;
                    $model->price = $price['price'];
                    $model->save(false);
                    $i++;
                }
                    $pay_info = [
                        'cost' => $price['price'],
                        'title' => 'title'];
                    return $this->render('payment', ['pay_info' => $pay_info]);
            }

but i siggest to explore also the batchInsert command http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail

For batch insert you can build an asscociative array with month and price eg:

 $my_array=   [
      ['January', 30],
      ['Febrary', 20],
      ['March', 25],
   ]

\Yii::$app->db->createCommand()->
       batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you it works. could you please show me this action using batchinsert?
Thanks a lot. it was useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.