Update an Entity with Unique Key - Insert instead of update

doctrine-orm, symfony

Solution

Can you persist new entity at all?

If you can, try merging your object instead:

public function updateCountry($p_entity) {
    var_dump($p_entity->getId());    //return 3 (as expected)
    var_dump(get_class($p_entity) ); //return Country (as expected)

    $this->em->merge($p_entity); // MERGE not PERSIST
    $this->em->flush();
}

From official docs:

If X is a new entity instance, a new managed copy X’ will be created and the state of X is copied onto this managed instance.

So, basically, `EntityManager::merge` can be used to both persist newly created object and merge exsistent one...

Problem

I have this method in my service: ``` public function updateCountry($p_entity) { var_dump($p_entity->getId()); //return 3 (as expected) var_dump(get_class($p_entity) ); //return Country (as expected) $this->em->persist($p_entity); $this->em->flush(); } ``` I call it by ``` $country = $em->getRepository('blabla')->find(3); $my_service->updateCountry($country); ``` But the request generated is Doctrine\DBAL\DBALException: An exception occurred while executing 'INSERT INTO country (code, label , created_at, updated_at) VALUES (?, ?, ?, ?)' with params ["EN", "England", "201 3-08-23 00:00:00", null]: I have a unique doctrine constraint this is my country.orm.yml ``` To\Bundle\Entity\Country: type: entity table: country repositoryClass: To\Bundle\Entity\CountryRepository fields: id: type: integer id: true generator: strategy: AUTO code: type: string length: 255 unique: true nullable: false ``` Why have I an insert request generated instead of the update one?

Original source