繁体   English   中英

symfony doctrine 无法在for循环中提交一个事务

[英]symfony doctrine cannot commit one transaction in for loop

我对这段代码有疑问:

foreach($commandes as $commande)
  $conn = $this->em->getConnection();
  $conn->beginTransaction();
  $conn->setAutoCommit(false);

  try {
    $tmp = $this->checkCommande($commande); // in this function there is multiple relationship created and pushed 

    if ($tmp) {
        $result = $tmp['result'];
        if ('OK' === $result) {
            $commande->setCompleted(true);
            $this->em->flush();
            $conn->commit();
        }
    }
  } catch (\Exception $e) {
    $conn->rollBack();
    throw $e;
  }
}

如果我有多个命令,并且如果一个未提交,则所有命令都不会提交。

您设置了一个条件,只有在'OK' === $result时才能提交命令。 如果不满足此条件,则会抛出异常并回滚更改。 要解决此问题,您应该将$conn->commit()调用移到此条件之外,除非抛出异常,否则始终会提交这些更改。 新代码可能如下所示:

foreach($commandes as $commande)
{
  $conn = $this->em->getConnection();
  $conn->beginTransaction();
  $conn->setAutoCommit(false);

  try {
    $tmp = $this->checkCommande($commande); // in this function there is multiple relationship created and pushed 

    if ($tmp) {
        $result = $tmp['result'];
        if ('OK' === $result) {
            $commande->setCompleted(true);
            $this->em->flush();
        }
    }

    $conn->commit(); // outside this line 
  } catch (\Exception $e) {
    $conn->rollBack();
    throw $e;
  }
}
 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM