Answer the question
In order to leave comments, you need to log in
How not to overwrite data when saving Doctrine?
Hello, sorry for the stupid question. How can I correctly save a record in the database so as not to overwrite data that may have changed at the time of receiving the Doctrine entity. In my case, this is some kind of statistics. Now I do this:
$this->entity_manager->getConnection()->beginTransaction();
$this->entity_manager->refresh($stats);
$stats->applyDeltaData();
$this->entity_manager->persist($stats);
$this->entity_manager->flush();
$this->entity_manager->getConnection()->commit();
Answer the question
In order to leave comments, you need to log in
cloud_zurbag : when you pull data from the entityManager, these very data (entities) start spinning in the Unit-of-work. When you pull flush, this same UoW (by default, the behavior is configurable) compares what happened, what happened, generates the corresponding SQL and commits the transaction (that is, all changes are already wrapped in a transaction, it is not clear why everything is wrapped manually in the question description again). Therefore, it is very easy, if you accidentally change the entity somewhere in the wrong place, to steal the data (unless the DBMS will let you complete the transaction).
romteh
The easiest way to deal with possible fakups is to remove the automatic addition of loaded entities to UoW, which will force the developer to always do persist (yes, by default, you can just flush when editing an already loaded entity).
Another option is to flush only what has changed:
the changes of only these two entities will be calculated and the transaction will be formed only for them. In this case, cascades, etc. are ignored.
But in general, I have a counter question for you, what does your statistics do in entities? It has no place there (unless, of course, this is part of the business logic).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question