Update an Entity with Unique Key - Insert instead of update

后端 未结 2 793
小鲜肉
小鲜肉 2021-01-14 11:19

I have this method in my service:

public function updateCountry($p_entity) {   


    var_dump($p_entity->getId());    //return 3 (as expected)
    var_du         


        
相关标签:
2条回答
  • 2021-01-14 11:51

    You shouldn't persist existing in DB entity, only new one. So if you get entity from DB and want to update it you should

    1. $entity->setName()
    2. $em->flush
    0 讨论(0)
  • 2021-01-14 11:58

    Can you persist new entity at all?

    If you can, try merging your object instead:

    public function updateCountry($p_entity) {
        var_dump($p_entity->getId());    //return 3 (as expected)
        var_dump(get_class($p_entity) ); //return Country (as expected)
    
        $this->em->merge($p_entity); // MERGE not PERSIST
        $this->em->flush();
    }
    

    From official docs:

    If X is a new entity instance, a new managed copy X’ will be created and the state of X is copied onto this managed instance.

    So, basically, EntityManager::merge can be used to both persist newly created object and merge exsistent one...

    0 讨论(0)
提交回复
热议问题