Doctrine 2 update from entity
You should call merge instead of persist:
$data = new MyEntity();
$data->setId(123);
$data->setName('test');
$entityManager->merge($data);
$entityManager->flush();
You can also use getReference
to update an entity property by identifier without retrieving the database state.
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#reference-proxies
This will establish a simple Proxy to work with the Entity by ID instead of instantiating a new Entity
or explicitly getting the Entity from the database using find()
, which can then be updated by flush.
$data = $entityManager->getReference('ATest', $id);
$data->setName('ORM Tested');
$entityManager->flush();
This is especially useful for updating the OneToMany
or ManyToMany
associations of an entity.
EG: $case->addTest($data);
It is generally bad practice to manually set the identifier of a new Entity, even if the intent is to update the entity. Instead it is usually best to let the EntityManager or Entity constructor establish the appropriate identifiers, such as a UUID
. For this reason Doctrine will generate entities by default with the identifier as a private property with no setter method.
I had to use
$entityManager->merge($data)