Insert multiple data into database in Yii 2

后端 未结 6 1220
死守一世寂寞
死守一世寂寞 2020-12-06 07:24

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 $         


        
相关标签:
6条回答
  • 2020-12-06 08:01
    foreach ($data as $key=>$value) {
       $model = new ModelNeme(); //optional
       $model->route = $_POST['name'][$key];
       $model->save();
    }
    return $this->redirect('index');
    
    0 讨论(0)
  • 2020-12-06 08:06
    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.

    0 讨论(0)
  • 2020-12-06 08:06

    You can use Yes It Is Batch Insert to insert multiple rows. It is faster than any of the ways stated 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();
    

    Check the link for this.

    0 讨论(0)
  • 2020-12-06 08:08
    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.
    0 讨论(0)
  • 2020-12-06 08:09

    I think batch insert is the best solution for this problem.

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

    solution for your code is

     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 讨论(0)
  • 2020-12-06 08:17

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

    0 讨论(0)
提交回复
热议问题