2012-11-07 37 views
2

我在value字段上有uniqueConstraints的測試實體。在Doctrine2中使用一次flush()插入之前執行UPDATE

我要添加一些新的測試實體,並更新現有的一些測試實體與一個flush(),如:

$new = new Test; 
$new->setValue('existing value'); 

$old = $em->getRepository('TestBundle:Test')->findOneByValue('existing value'); 
$old->setValue('new value); 

$em->flush(); 

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'existing value'

這是因爲舊的實體未插入新的實體之前更新。

是否可以使用ONE flush()?

+0

請問你是怎麼處理這個問題的?我有同樣的問題,迄今爲止唯一的解決方案是想禁用UQ常量,並確保在驗證級別上實體是唯一的。 –

回答

0

我不這麼認爲。 Flush正在執行UnitOfWork :: commit方法,該方法首先執行插入操作,然後執行更新操作:

try { 
     if ($this->entityInsertions) { 
      foreach ($commitOrder as $class) { 
       $this->executeInserts($class); 
      } 
     } 

     if ($this->entityUpdates) { 
      foreach ($commitOrder as $class) { 
       $this->executeUpdates($class); 
      } 
     } 

     // Extra updates that were requested by persisters. 
     if ($this->extraUpdates) { 
      $this->executeExtraUpdates(); 
     } 

     // Collection deletions (deletions of complete collections) 
     foreach ($this->collectionDeletions as $collectionToDelete) { 
      $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete); 
     } 
     // Collection updates (deleteRows, updateRows, insertRows) 
     foreach ($this->collectionUpdates as $collectionToUpdate) { 
      $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate); 
     } 

     // Entity deletions come last and need to be in reverse commit order 
     if ($this->entityDeletions) { 
      for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) { 
       $this->executeDeletions($commitOrder[$i]); 
      } 
     } 

     $conn->commit(); 
    } catch (Exception $e) { 
     $this->em->close(); 
     $conn->rollback(); 

     throw $e; 
    } 
相關問題