I'm trying to save a lot of CActiveRecord model objects in a loop. I have something like this:
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$object->save();
}
In my case, this creates about 400 CActiveRecord objects. The saving process is really slow, because each save() queries the database.
Is there a way to save all those objects in one go? Something like:
$objects = array();
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$objects[] = $object;
}
save_all_objects($objects);
I could not find anything on the subject. Anyone?
you can
validate()
your model, and if it was ok you can append it so a sql text for insert,and after your loop, just use databases
commandBuilder()
and execute your prepared textFor insert multi rows, Put this code in
components
folder underGeneralRepository.php
file name.And usage anywhere:
https://www.yiiframework.com/extension/yii-insert-multi-rows
Since v1.1.14, the method
createMultipleInsertCommand()
ofCDbCommandBuilder
class is available.