Doctrine 2 update from entity

前端 未结 4 1822
梦谈多话
梦谈多话 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:26

    You should call merge instead of persist:

    $data = new MyEntity();
    $data->setId(123);
    $data->setName('test');
    
    $entityManager->merge($data);
    $entityManager->flush();
    
    0 讨论(0)
  • 2020-12-23 11:30

    I had to use

    $entityManager->merge($data)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-23 11:44

    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 讨论(0)
提交回复
热议问题