I want to insert multiple record in my table using yii2 ActiveRecord. I already know that I can use this code
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
but by this approach my model validations are not executing. and I already have read this question ActiveRecord batch insert (yii2)
but also by doing validation in a tricky way, consider I want to fill created_at
and updated_at
columns using ActiveRecords events.
just like this
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if($insert)
$this->created_at = date('Y-m-d H:i:s');
$this->updated_at = date('Y-m-d H:i:s');
return true;
} else {
return false;
}
}
I think is not good idea to use
beforeSave
events (and similar stuff) because it will trigger for each model. However you want save multiple models at once. I recommend to use bulk methods.In similar cases I use usually following "bulk" approach (code not tested, just for example):
This class can be used:
Additionally, for more convenient working with multiple models can be developed special
Collection
class that implements\ArrayAccess
and\Iterator
interfaces. This collection can iterated as simple array, however it contains special methods for bulk operations. Something like this: