Mohammad Aghayari
Mohammad Aghayari

Reputation: 1160

Insert multi record to database with yii2

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]);
                }

Upvotes: 0

Views: 373

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133380

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();

Upvotes: 1

Related Questions