1

I am using batchInsert() function of Yii2 Database Access Objects. I need to run another function like sending email from PHP code after each record is inserted.What is the workaround to achieve this? Or is it possible to get all AUTO_INCREMENT ids of rows inserted? The code is

Yii::$app->db->createCommand()->batchInsert(Address::tableName(), 
['form_id','address'], $rows)->execute();

I am using batchInsert() documented in https://www.yiiframework.com/doc/api/2.0/yii-db-command#batchInsert()-detail

user7282
  • 5,106
  • 9
  • 41
  • 72

1 Answers1

1

First, you're not using ActiveRecord. More about ActiveRecord you can find in the documentation: API and guide. Yii::$app->db->createCommand() is a DAO which is much simpler than ActiveRecord and does not support events in the same way.

Second, there is no batchInsert() for ActiveRecord and there is a good reason for that - it is hard to detect IDs of inserted records when you're inserting them in batch (at least in a reliable and DB-independent way). More about this you can read at GitHub.

However if you know IDs of records or some unique fields before insert (for example user in addition to the numeric ID, it also has a unique login and/or email), you may just fetch them after insert and run event manually:

$models = Address::findAll(['email' => $emailsArray]);
foreach ($models as $model) {
    $model->trigger('myEvent');
}

But unless you're inserting millions of records, you should probably stick to simple foreach and $model->save(), for the sake of simplicity and reliability.

There is also a yii2-collection official extension. This is still more like a draft and POC, but it may be interesting in the future.

rob006
  • 21,383
  • 5
  • 53
  • 74