Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
486 views
Welcome To Ask or Share your Answers For Others

1 Answer

  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...