我在uniqueConstraints
字段上有value
的测试实体。
我想添加一些新的Test实体并使用一个flush()
更新一些现有的Test实体,如:
$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 :(得分: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;
}
答案 1 :(得分:0)
您不应该添加$ em-> persist($ new);在$ new-> setValue('existing value');之后吗?