Created
April 3, 2017 07:10
-
-
Save mikemadisonweb/fe881b7254f812ec4dc545d5baaec839 to your computer and use it in GitHub Desktop.
ActiveRecod batch insert realization in Yii2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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