Quite often you may encounter a race condition when an entry already exists in the database and inserting another one causes unique constraint failure. Dbal converts this database error into a UniqueConstraintViolationException
, so you may catch it and mitigate it.
In the example below, the persist action may fail because there is already a like for a specific author & article.
try { $like = new Like(); $like->article = $article; $like->author = $author; $this->orm->likes->persistAndFlush($like); } catch (\Nextras\Dbal\Drivers\Exception\UniqueConstraintViolationException $e) { $this->orm->likes->getMapper()->rollback(); $this->orm->refreshAll() }