How to check if entity changed in Doctrine 2?

前端 未结 9 720
盖世英雄少女心
盖世英雄少女心 2020-12-23 20:53

I need to check if a persisted entity has changed and needs to be updated on the database. What I made (and did not work) was the following:

$product = $enti         


        
9条回答
  •  [愿得一人]
    2020-12-23 21:16

    The issue is quite old but there may be still some group of people that might face this problem from a different point of view. The UnitOfWork works great but it only returns the array of changes. It can be a pain in butt when someone doesn't actually knows which fields may have changed and just wants to get the whole entity as an object to compare $oldEntity and $newEntity. Even though the event's name is preUpdate if someone will try to fetch the data from the database as follows:

    $er->find($id);
    

    the returned entity will contain all changes. The workaround is quite simple but it has some hooks:

    public function preUpdate(Entity $entity, PreUpdateEventArgs $args)
    {
        $entity = clone $entity; //as Doctrine under the hood 
                                 //uses reference to manage entities you might want 
                                 //to work on the entity copy. Otherwise,        
                                 //the below refresh($entity) will affect both 
                                 //old and new entity.
        $em = $args->getEntityManager();
        $currentEntity = $em->getRepository('AppBundle:Entity')->find($entity->getId());
        $em->refresh($currentEntity);
    
    }
    

    For those who are using another event, like preFlush, I've quickly checked it and the workaround didn't work well because probably the refresh() method discards any flush changes so what needs to be done is to call the flush once again in listener and create some static $alreadyFlushed toggle to avoid circular reference.

提交回复
热议问题