Insert multiple data into database in Yii 2
Asked Answered
T

6

7

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.

Tillage answered 26/3, 2015 at 6:13 Comment(2)
you can use batchInsert() to insert multiple records at a time. For more details: yiiframework.com/doc-2.0/…Sublimation
@chinmay thank you, is so usefullTillage
F
12
  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.

Fuselage answered 26/3, 2015 at 9:0 Comment(1)
This works fine. You can get tableName using YourModelName::getTableSchema()->nameLear
A
3

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

Avery answered 26/3, 2015 at 6:45 Comment(2)
Not when you use Yii's db command. yiiframework.com/doc-2.0/yii-db-command.html - Using an object in a loop would be very inefficient and a terrible solution, especially for potentially large amounts of data. Your really going to load an object 1,000 times in a loop to import 1,000 items? Here is a side-by-side breakdown showing the differences and uses: bsourcecode.com/yiiframework2/insert-query - To the op, look at the batch insert as @Fuselage answered. For really large imports, split the data into batches of say 500/loop.Acceptor
Question: One of the API's I am using (which is awful) returns all records (about 3,000 in total) - i want to do a batch upload but only of new records and altered records, how would i do that without a foreach loop?Musical
B
2
  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.
Bibliographer answered 26/3, 2015 at 6:55 Comment(1)
isn't it going to shortened our store life? cz if i have 250000 data then i need to write 250000 times to my storage, rather than just write one time with bigger size to write? or is it will gave the same result to our storage??Brockie
P
1

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.

Prosy answered 2/2, 2018 at 17:42 Comment(0)
G
0

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');
Gagger answered 29/3, 2018 at 19:14 Comment(0)
S
0
foreach ($data as $key=>$value) {
   $model = new ModelNeme(); //optional
   $model->route = $_POST['name'][$key];
   $model->save();
}
return $this->redirect('index');
Sarsaparilla answered 13/11, 2020 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.