'Integrity constraint violation on loading an entity and saving it back to the DB [duplicate]

I'm facing a strange issue following code is causing an Integrity constraint violation error

$myEntity = $this->myRepository->findOneBy(['id' => $myId]);
$myEntity->setStatus(false);
$this->entityManager->persist($myEntity);
$this->entityManager->flush();

The above code is causing the following error

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'value_2' for key 'UNIQ_DFBBD17E7927C74'

As per my understanding, this should not happen, we are loading an entity from the DB and saving it back. How it can cause an Integrity constraint violation error?



Solution 1:[1]

I'm not sure, if you use Doctrine, but there is an difference of using "persist" (insert new entity) or "merge" (update an entity). This should work:

$this->entityManager->merge($myEntity);

Remember: merge returns the copy of the saved entity, whereas persist returns nothing.

You can find some good examples here: https://hotexamples.com/examples/doctrine.orm/EntityManager/persist/php-entitymanager-persist-method-examples.html

https://hotexamples.com/examples/doctrine.orm/EntityManager/merge/php-entitymanager-merge-method-examples.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sven