R
R
Roman2015-06-01 11:10:15
PHP
Roman, 2015-06-01 11:10:15

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();

How correct is this? As far as I understand, update and write requests will be executed sequentially?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-06-17
Protko @Fesor

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 question

Ask a Question

731 491 924 answers to any question