Doctrine 2 update from entity
Is it possible to update an entity in a similar way as below:
$data = new ATest(); // my entity
$data->id = 1; // id 1 already exists, I just want to update this row
$data->name = "ORM Tested"; // changed the name
$entityManager->persist($data);
$entityManager->flush();
This will insert and change the id of the object instead of updating the existing row in the database开发者_StackOverflow.
You should call merge instead of persist:
$data = new MyEntity();
$data->setId(123);
$data->setName('test');
$entityManager->merge($data);
$entityManager->flush();
I had to use
$entityManager->merge($data)
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.
Or just get the managed entity rather than an empty one.
$data = $entityManager->getRepository('ATest')->findOne(1); // ATest is my entitity class
$data->name = "ORM Tested"; // just change the name
$entityManager->persist($data);
$entityManager->flush();
If the entity is already managed, persist() will update it rather than insert a new one.
精彩评论