【问题标题】:manytoone doctrine in symfony2symfony2 中的多联机原则
【发布时间】:2012-11-10 02:10:39
【问题描述】:

我有很多相关的用户和组,然后删除在我得到的用户中使用的组:

DBALException:执行“DELETE FROM”时发生异常 组 WHERE id = ?'带参数...违反完整性约束: 1451 无法删除或更新父行:外键约束 失败...

DBALException:执行“DELETE FROM”时发生异常 组 WHERE id = ?'带参数...违反完整性约束: 1451 无法删除或更新父行:外键约束 失败

... 这很正常,我怎样才能捕获异常,或者检查它是否以某种方式使用?

【问题讨论】:

    标签: exception symfony doctrine


    【解决方案1】:

    这意味着您可能已经使用外键设置了数据库,如下所示:

    |---------|
    | User    |
    |---------|
    | id      |
    | groupId |
    |---------|
    
    |-------|
    | Group |
    |-------|
    | id    |
    |-------|
    

    其中User.groupId 指的是Group.id。这意味着当您删除一个组时,您需要定义数据库应该对属于该组的用户做什么。

    根据您的意图,可以更改您的外键约束来处理这种情况。你没有提到你正在使用什么数据库类型,但我知道在 MySQL 中你可以有一个 CONSTRAINT 和一个 ON DELETE 子句,并给它 RESTRICT 的选项(默认,你所看到的现在)、CASCADE(删除与该组关联的所有用户)和SET NULL(将groupId 设置为NULL,用于删除组的用户)。

    【讨论】:

      【解决方案2】:

      除了在数据库级别使用ON DELETE 子句(这显然是优雅且独立于框架的方式)之外,您可能希望直接在代码中检查组的现有用户。在这种情况下,您可以执行另一个查询。

      $em = $this->getDoctrine()->getEntityManager();
      
      // Set your group id as the desired criterion
      $criteria = array('GroupId' => $group->getId);
      
      // Get all users that match the criterion
      $users = $em->getRepository("YourBundle:User")->findBy($criteria);
      
      // Check whether the returned array is empty
      if(count($users) != 0){
          // Do your exception handling
      }else {
          // Do regular operations, like deleting the group
      }
      

      【讨论】:

        【解决方案3】:

        如果你想在删除组时删除组内的所有用户,你可以告诉学说级联删除。所以元数据文件的 oneToMany 部分(比如 groups.orm.yml)看起来像

        oneToMany:
            users:
                targetEntity: Users
                mappedBy: user
                cascade: [remove]
        

        更多信息在这里http://docs.doctrine-project.org/en/2.0.x/reference/working-with-associations.html#transitive-persistence-cascade-operations

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多