I have a function that looks like this:
function findByAndCreateIfNotExists($criteria){ $entity = $this->findBy(['criteria'=>$criteria]); // this is the problem area, if request 1 is still creating the entity, request 2 won't find it yet. if (! $entity) { $entity = $this->createEntity($criteria); } return $entity; }
This function is used by various queries, and I found that simultaneous queries sometimes try to create the same object by throwing a DBALException , complaining about duplicate entries for a unique key.
I was thinking about LOCK TABLES , as mentioned here: How to lock the whole table in symfony2 using doctrine2?
But just given the fact that there is no function in the Doctrine, I assume that this is not the preferred method. My question is: how can I prevent concurrent requests trying to create the same object and always return the correct one?
php mysql symfony doctrine2
mickadoo
source share