Yii2 Batch Insert

865 Views Asked by At

I want to insert multiple columns at a time. I am getting data from the api and i want to insert the thousands of row at a time. How can i do it?

I tried the following

 if(is_array($did))
                {
                    $row=array();
                    foreach ($did as $di) 
                    {
                    
                      $row[]=$di['src'];
                      $row[]=$di['dst'];
                      $row[]=$di['disposition'];
                      $row[]=$di['cost'];
                      $row[]=$di['date'];
                       
                    }
                }
                Yii::$app->db->createCommand()->batchInsert('call_records', ['source', 'destination','disposition','cost','date_added'], [$row])->execute();

but i guess it is not inserting. the second argument needs to be set of arrays i am not able to make it.

Kindly let me know what can be done

Thanks

1

There are 1 best solutions below

0
ScaisEdge On BEST ANSWER

Seems you have wrong rows assignment try use this way

if (is_array($did)) {
     $row=array();
     foreach ($did as $di) {
        
          $row[]= [
            'source'        => $di['src'], 
            'destination'   => $di['dst'],
            'disposition'   => $di['disposition'],
            'cost'          => $di['cost'],
            'date_added'    => $di['date'],
          ];
                   
    }
}

$columns = ['source', 'destination','disposition','cost','date_added'];

Yii::$app->db->createCommand()
    ->batchInsert('call_records', $columns, $row)
    ->execute();