Skip to content

Instantly share code, notes, and snippets.

@mikemadisonweb
Created April 3, 2017 07:10
Show Gist options
  • Save mikemadisonweb/fe881b7254f812ec4dc545d5baaec839 to your computer and use it in GitHub Desktop.
Save mikemadisonweb/fe881b7254f812ec4dc545d5baaec839 to your computer and use it in GitHub Desktop.
ActiveRecod batch insert realization in Yii2
namespace common\components;
class Model extends yii\base\Model {
/**
* Saves multiple models.
*
* @param ActiveRecord[] $models
* @return bool
*/
public static saveMultiple($models){
if(count($models) > 0){
$firstModel = reset($models);
$columnsToInsert = $firstModel->attributes(); // here you can remove excess columns. for example PK column.
$modelsToInsert = [];
$rowsToInsert = [];
foreach($models as $model){
if ($this->beforeSave(true)) {
$modelsToInsert[] = $model;
}
}
foreach($modelsToInsert as $model){
$rowsToInsert[] = array_values($model->attributes); // here you can remove excess values
}
$numberAffectedRows = \Yii::$app->db->createCommand()
->batchInsert($firstModel->tableName(), $columnsToInsert, $rowsToInsert)
->execute();
$isSuccess = ($numberAffectedRows === count($models));
if($isSuccess){
$changedAttributes = array_fill_keys($columnsToInsert, null);
foreach($modelsToInsert as $model){
$model->afterSave(true, $changedAttributes);
}
}
return $isSuccess;
} else {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment