如何在Yii中将保存模型移到循环外?

时间:2015-06-26 21:32:25

标签: activerecord yii

我需要移出一个$model->save()句子的循环,例如:

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

无法将模型保存在循环外部?我的意思是如果$nodes中有100000条记录,保存方法将被执行100000次? 谢谢!

2 个答案:

答案 0 :(得分:1)

没有任何其他解决方案。如果你有100,000条记录,你必须迭代100,00次! 您也可以使用CDbCommand以这种方式更快地响应:

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

答案 1 :(得分: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();