【问题标题】:Symfony2, Doctrine2, EntityManager disable last actionsSymfony2、Doctrine2、EntityManager 禁用最后的操作
【发布时间】:2013-05-22 15:42:42
【问题描述】:

我们有

foreach ($rwst as $row)
{
    $loopData = XmlFunctions::getXmlAttrAsArray($row);
    if (!$loopData)
    {
        return false;
    }

    $oCharacters = new XmlAccountCharacters();
    $oCharacters
            ->setKeyID($this->keyID)
            ->setCharacterID($loopData['characterID'])
            ->setCharacterName($loopData['name'])
            ->setCorporationID($loopData['corporationID'])
            ->setCorporationName($loopData['corporationName']);

    $this->sEntityManager->persist($oCharacters);
}

$this->sEntityManager->flush();

关键是我们什么时候会有 FALSE

$loopData

我们将退出当前函数。但。图像我们将在 foreach 中的第二个项目上设置错误,因此第一个实体将被持久化到 EntityNamager。我怎样才能把它弄出来?因为 next(即使在另一个服务\控制器中)->flush() 会保存它,我们不想要它。

【问题讨论】:

  • 您想撤消持久调用吗?如果你真的想保存,你应该只调用persist
  • 不是,你自己试试吧,正如我所说,无论从哪个控制器调用 flush() - 它都会将我们的实体插入到数据库中。
  • 作为一个简单的例子,尝试在一个服务中持久化,然后在另一个服务中调用flush,将插入第一个实体中的实体
  • jeah 那是所需的行为,因此如果您在多个服务中编辑多个实体,则不必刷新和查询数据库。那有什么问题?如果您想要一个新实体并绝对将其保存到数据库中,您应该只调用persist ... .

标签: loops symfony doctrine-orm entitymanager


【解决方案1】:

您正在寻找的是显式交易。看看Doctrine-documentation。基本上你的代码应该是这样的:

$this->sEntityManager->getConnection()->beginTransaction();
try {
    foreach ($rwst as $row) {
        $loopData = XmlFunctions::getXmlAttrAsArray($row);
        if (!$loopData) {
            throw new SomeException();
        }
        \\ the rest of your code
        $this->sEntityManager->persist($oCharacters);
    }
    $this->sEntityManager->flush();
    $this->sEntityManager->getConnection()->commit();
    return true;
} catch (SomeException $e) {
    $this->sEntityManager->getConnection()->rollback();
    $this->sEntityManager->close();
}
return false;

【讨论】:

  • 很好的例子,但它是交易,我不需要它 atm,反正我找到了答案
【解决方案2】:

一如既往,asnwer 比我想象的要简单得多。 =\

if(!$loopData)
{
    $this->sEntityManager->clear()
    return false;
}

并且所有持久化的实体都将脱离教义,因此它们不会被插入\更新。 或单个实体

$this->sEntityManager->detach($entity);

http://doctrine-orm.readthedocs.org/en/2.0.x/reference/batch-processing.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2014-10-06
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多