phpmongodbdoctrinedoctrine-odm

Altering another document in Doctrine ODM PreUpdate event


Fairly new at MongoDB and Doctrine both. I'm currently setting up a model system for my framework, and trying to implement the events.

The idea is this: When a certain model gets updated, a new user (also a model) should be created/updated. I do this all in the PreUpdate event so I can catch the changes made (check if the e-mail address on the model has been changed).

Creating and persisting a new model in this event works like a charm, however when I try to update a user I'm unable to save the data. I tried flushing but this causes an infinite loop (which I can understand why, as he tries to flush the same document again).

Any ideas on what way I should get this done? Tried recomputeSingleDocumentChangeSet on the unit of work for the user, but this doesn't seem to save anything.


Solution

  • Tried recomputeSingleDocumentChangeSet on the unit of work for the user, but this doesn't seem to save anything.

    This is exactly what you should do (after modifying the user field)

    $user->setSomething(true);
    $uow->recomputeSingleDocumentChangeSet(/* ... */);
    

    and nothing else, especially don't use flush as you are inside flush already. The recomputeSingleDocumentChangeSet makes Doctrine recount changes which will be later included in the update query of document.

    Creating and persisting a new model in this event works like a charm

    This however sounds strange as new objects persisted at the time of preUpdate event should not reach database (unless you have issued another flush which may have unwanted side effects at this point) as insertions are handled before updates.