【问题标题】:Doctrine2 ORM EntityManager fetch an occuring errorDoctrine2 ORM EntityManager 获取发生的错误
【发布时间】:2014-10-07 22:09:20
【问题描述】:

我有一个名为 Theme 的实体,它的名字不是 Id,而是应该被索引并且是唯一的:

/**
 * @Entity @Table(name="themes",
 *                uniqueConstraints={@UniqueConstraint(name="theme_unique",columns={"name"})},
 *                indexes={@Index(name="theme_idx", columns={"name"})})
 */
class Theme {...}

我使用现有名称创建了一个新主题。这会产生错误,脚本停止。 我应该如何获取该错误并继续执行脚本?

function CreateTheme($newThemeName) {
    //$theme = $this->FindByThemeName ( $newThemeName );
    //if (! $theme) {
        $theme = new Theme ();
        $theme->setName ( $newThemeName );
        $theme->setIsActive ( false );
        $theme->setIsDefault ( false );
        $this->entityManager->persist ( $theme );
        $this->entityManager->flush ();
        return $theme;
    //} else {
    //  $this->error = "Error in flush was avoided (name not being unique)!";
    //  return null;
    //}

【问题讨论】:

    标签: error-handling doctrine-orm entitymanager flush


    【解决方案1】:

    try/catch 设置并不能真正解决问题:

    Doctrine\ORM\EntityManager 由于 SQL 错误而关闭。 EntityManager 不能简单地重置(或重新打开)。关于这个主题的链接:

    The EntityManager is closed

    声明:“最好避免获得封闭的实体管理器(这意味着在将数据发送到数据库之前验证您的数据)”

    结论:设置 UniqueConstraints 的注释是无用的:它不会阻止执行语法有效的 SQL 指令,该指令会由于该约束而给出“重复条目”SQL 错误。 此错误关闭无法安全重置的 EntityManager.... 在尝试持久化和刷新新实体实例之前,您需要“手动”检查是否违反了唯一约束。

    【讨论】:

      【解决方案2】:

      Try Catch 不起作用,这就是这个问题的原因。

      ORMException 的处理程序不知何故未注册,现在注册了。不清楚是什么原因造成的。

      function CreateTheme($themeName) {
          global $entityManager;
          $theme = new Theme ();
          $theme->setName ( $themeName );
          $theme->setIsActive ( false );
          $theme->setIsDefault ( false );
          try {
              $entityManager->persist ( $theme );
              $entityManager->flush ();
          } catch (Exception $e) {
              echo $e->getMessage();
              $theme = null;
          }
          return $theme;
      }
      

      使用重复名称时给出:

      SQLSTATE[23000]:违反完整性约束:1062 键“theme_unique”的重复条目“test”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-25
        • 2012-09-03
        • 2019-11-12
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        • 2016-05-20
        • 1970-01-01
        相关资源
        最近更新 更多