activerecordyii2batch-insert

Yii2 Batch Insert


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


Solution

  • 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();