Insert multiple data into a database in Yii 2

I have a problem with my code, when I try to save several data in the database at the same time, this is my code to save in the database:

foreach ($data as $value) { $model->route = $value[0][1]; $model->begin_point = $value[0][2]; $model->begin_point = $value[0][3]; $model->save(); } return $this->redirect('index'); 

every thing i try to save, i only get the last data array that can be stored in the database. can someone help me? or if someone can provide a tutorial, this will be a real help.

+5
source share
5 answers
  1. Create an array by looping multiple values.

     $data- has multiple values $bulkInsertArray = array(); foreach($data as $value){ $bulkInsertArray[]=[ 'columnName1'=>$value[0][1], 'columnName2'=>$value[0][2], 'columnName3'=>$value[0][3] ]; } 
  2. Check $ bulkInsertArray for not empty

     if(count($bulkInsertArray)>0){ $columnNameArray=['columnName1','columnName2','columnName3']; // below line insert all your record and return number of rows inserted $insertCount = Yii::$app->db->createCommand() ->batchInsert( $tableName, $columnNameArray, $bulkInsertArray ) ->execute(); } 

Hope this code can be helpful.

+8
source

You must create a new model object each time. Or Else youre Just a rewriting.

+3
source
  • To achieve this, you can use the Yii command constructor.
 $command = Yii::app()->db->createCommand(); $command->insert('table_name',array('column_1'=>$value_1), 'column_2'=>$value_2)); 

etc.

  1. Write this code in a loop and it will insert all the records one by one.
+2
source

You can use Yes It Batch Insert to insert multiple lines. This is faster than any of the methods described here:

 $connection->createCommand()->batchInsert('table_name', ['table_column_1', 'table_column_2'], [ ['column_1_data_a', 'column_2_data_a'], ['column_1_data_b', 'column_2_data_b'], ['column_1_data_c', 'column_2_data_c'], ])->execute(); 

Mark the link for this .

0
source

I think batch insertion is the best solution to this problem.

but there is one problem with your code drawing , this code will create only one row of data (first row) in the data table and update it to the same model

solution for your code

  foreach ($data as $value) { $model = new Model(); // creating new instance of model $model->route = $value[0][1]; $model->begin_point = $value[0][2]; $model->begin_point = $value[0][3]; $model->save(); } return $this->redirect('index'); 
0
source

Source: https://habr.com/ru/post/952768/


All Articles