Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple data into database in Yii 2

Tags:

php

yii2

I have problem with my code when i'm trying to save multiple data into database at the same time, this is my code to save into 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 i'm trying to save, i'm only get the last data array can save into database. could someone help me? or if someone could provide a tutorial, that would be a real help.

like image 293
Shinoda_ Avatar asked Mar 26 '15 06:03

Shinoda_


3 Answers

  1. Create an array by looping your 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 in 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 these code may be helpful.

like image 168
Kailas Avatar answered Sep 20 '22 21:09

Kailas


You have to create a New object of the model each time. Or Else youre Just overwriting.

like image 37
Jørgen Avatar answered Sep 21 '22 21:09

Jørgen


  1. You can use Yii command builder to achieve this.
$command = Yii::app()->db->createCommand();

$command->insert('table_name',array('column_1'=>$value_1),
'column_2'=>$value_2));

and so on.

  1. Write this code in loop and it will insert all records one after another.
like image 35
kammy Avatar answered Sep 19 '22 21:09

kammy