Doctrine 2 update from entity

前端 未结 4 1842
梦谈多话
梦谈多话 2020-12-23 11:11

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,         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-23 11:36

    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.

提交回复
热议问题