orm icon indicating copy to clipboard operation
orm copied to clipboard

Cannot persist an entity during onFlush

Open yann-eugone opened this issue 8 months ago • 2 comments

Bug Report

Q A
Version 3.3.2
Previous Version if the bug is a regression

Summary

Not able to persist a new entity in the onFlush listener.

Current behavior

When using EntityManager::persist() along with UnitOfWork::computeChangeSet(), I get a SQL syntax error: the insert query does not have any parameter bound.

When using Collection::add() along with UnitOfWork::recomputeSingleEntityChangeSet(), nothing happens: the entity is never saved.

Expected behavior

Regarding the documentation, we should be able to persist new entities, on their own, or using collections:

The following restrictions apply to the onFlush event:

  • If you create and persist a new entity in onFlush, then calling EntityManager::persist() is not enough. You have to execute an additional call to $unitOfWork->computeChangeSet($classMetadata, $entity).
  • Changing primitive fields or associations requires you to explicitly trigger a re-computation of the changeset of the affected entity. This can be done by calling $unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity).

How to reproduce

I created a pretty simple project with my use case https://github.com/yann-eugone/doctrine-persist-in-onflush

The idea is that I have a AuditEvent entity that should be created every time an entity is updated.

yann-eugone avatar Mar 27 '25 12:03 yann-eugone

#10900 is related.

Are you seeing #10869 here?

mpdude avatar Mar 30 '25 21:03 mpdude

Not sure it is related, not doing any flush during the event listener Tried to downgrade doctrine/orm on the project, never been able to see it work as expected

yann-eugone avatar Mar 31 '25 09:03 yann-eugone

I think I found the reason why it do fails My model is not that simple I wrote in the description I do have an AuditEvent entity that represent an update event But that entity has a collection of to AuditEventRelation entities, that represent payload parts when updated value are entities and not scalar The exception I get with the persist strategy is when Doctrine try to insert these relations

I had to manually persist these relations to in order to make it work

foreach ($event->getRelations() as $relation) {
    $entityManager->persist($relation);
    $unitOfWork->computeChangeSet($eventRelationMetadata, $relation);
}

https://github.com/yann-eugone/doctrine-persist-in-onflush/commit/5dac0ce5030dc417a46b83e7ce93c4d6cb954979

I still have no idea how to fix the record strategy

yann-eugone avatar Apr 01 '25 08:04 yann-eugone

I believe I've found a solution to the problem I've faced You can close it if you want

Is still believe that the error was very unclear

yann-eugone avatar Apr 02 '25 12:04 yann-eugone