开发者

Doctrine 2 update from entity

开发者 https://www.devze.com 2023-02-24 01:17 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消