2

uniqueConstraintsvalue现场有测试实体。

我想添加一些新的 Test 实体并使用以下内容更新一些现有的 Test 实体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() 来做到这一点?

4

2 回答 2

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;
    }
于 2012-11-07T09:53:29.000 回答
-1

你不应该添加 $em->persist($new); 在 $new->setValue('现有值');?

于 2020-09-24T13:44:28.750 回答