0

I need to move outside a loop the $model->save() sentence, by example:

foreach ($nodes as $i => $node) { 
    $model = new Singer();
    $model->name = $node['name'];
    $model->birthDate = $node['birthDate'];
    $model->save();
}

There is no way to save the model outside the loop? I mean if there is 100000 records in $nodes the save method will be executed 100000 times?? Thank you!

Andre L.
  • 3
  • 1
  • possible duplicate of [Yii: save multiple records in one query](http://stackoverflow.com/questions/21292126/yii-save-multiple-records-in-one-query) – Developerium Jun 27 '15 at 04:54
  • http://stackoverflow.com/questions/21292126/yii-save-multiple-records-in-one-query/21299977#21299977 – Developerium Jun 27 '15 at 04:55

2 Answers2

1

There isn't any other solution. If you have 100,000 records, you have to iterate 100,00 times! You can also use CDbCommand for faster response in this way:

$values = "";
foreach ($nodes as $i => $node) {
     $values.= "(". $node['name'] . "," . $node['birthDate'] . ")" . ",";
}
$values = rtrim($values, ",") //remove last "," from $values
$sql = 'ISERT INTO "singer"(name, birthDate) VALUES '.$values;
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
hamed
  • 7,939
  • 15
  • 60
  • 114
  • I upvoted, but want to warn against a too large string in values. I would consider creating an array of insert clauses in the loop and use join() instead of rtrim. – crafter Jun 27 '15 at 09:38
1
    $values = array();

    foreach ($nodes as  $node) {
        $values[]=array(
            'name' => $node['name'],
            'birthDate' => $node['birthDate']
        );
    }

    Yii::app()->db->schema->getCommandBuilder()->createMultipleInsertCommand(Singer::model()->tableName(), $values)->execute();
Double H
  • 4,120
  • 1
  • 15
  • 26