The EntityManager is closed

前端 未结 17 1729
星月不相逢
星月不相逢 2020-11-29 18:36
[Doctrine\\ORM\\ORMException]   
The EntityManager is closed.  

After I get a DBAL exception when inserting data, EntityManager closes and I\'m not

17条回答
  •  情深已故
    2020-11-29 18:57

    Symfony v4.1.6

    Doctrine v2.9.0

    Process inserting duplicates in a repository

    1. Get access a registry in your repo
    
    
        //begin of repo
        
        /** @var RegistryInterface */
        protected $registry;
        
        public function __construct(RegistryInterface $registry)
        {
            $this->registry = $registry;
            parent::__construct($registry, YourEntity::class);
        }
    
    
    1. Wrap risky code into transaction and reset manager in case of exception
    
    
        //in repo method
        $em = $this->getEntityManager();
        
        $em->beginTransaction();
        try {
            $em->persist($yourEntityThatCanBeDuplicate);
            $em->flush();
            $em->commit();
        
        } catch (\Throwable $e) {
            //Rollback all nested transactions
            while ($em->getConnection()->getTransactionNestingLevel() > 0) {
                $em->rollback();
            }
            
            //Reset the default em
            if (!$em->isOpen()) {
                $this->registry->resetManager();
            }
        }
    
    

提交回复
热议问题