Skip to content
Advertisement

Doctrine ORM: Ignore all events with persist and flush

I’m working on a system which uses doctrine/orm 2.6 (PHP 7.1 & MySQL 5.7) and am trying to update a large number of entities using the following code:

foreach ($entities as $entity) {
  $this->getEntityManager()->persist($entity);
  $this->getEntityManager()->flush();
}

The issue I’m running into is that the entities have lots of lifecycle events registered (preUpdate, prePersist, postUpdate, postPersist), and some of these events involve expensive operations which aren’t necessary when doing a mass update.

Is there a way to tell Doctrine to ignore all events when I call persist and flush on a per-call basis (I don’t want to this behaviour globally)?

The other options I have considered are:

Not adding the events in the first place: This is difficult because they are spread all over the system and are setup early on the application bootstrapping, before the point at which the application knows whether they are needed. Ideally I want to keep the “ignore events” option as close to the code that uses it, rather than spreading it all over the system.

Using DQL (or SQL) queries instead of entities: Everything else in the system uses entities so I’d prefer to be consistent if possible (if not I will fall back to this option).

Advertisement

Answer

The linked question posted by @Shiers (Doctrine 2 – Disable PrePersist from outside of entity) gave me two conflicting answers – the ones with the most upvotes suggested it was possible to remove the events, whereas the accepted one states this is not possible. I tried the removal options and they did not work.

Therefore the answer to this question is that the events can’t be removed and the only option is to drop into SQL. That’s what I did in this case and it worked, albeit at the cost of having to remember to manually update some columns that would be handled by the ORM (e.g. updatedAt).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement