【问题标题】:Symfony 1.4 Doctrine schema help required to resolve Integrity constraint violationSymfony 1.4 Doctrine 模式帮助需要解决完整性约束违规
【发布时间】:2012-01-01 03:58:18
【问题描述】:

目标:当一个用户被删除时,用户在 UserCategory 中的所有条目也应该被删除。

架构:

User:
  actAs: { Timestampable: ~ }
  columns:
    first_name: { type: string(255) }
    name: { type: string(255) }
    company: { type: string(255) }
    email: { type: string(255) }
    phone: { type: string(255) }
    language_id: { type: integer, notnull: true }
    token: { type: string(255) }
    activated: { type: boolean, default: false }
  relations:
    Categories:
       class: Category
       local: user_id
       foreign: category_id
       refClass: UserCategory
       type: many

UserCategory:
  actAs: { Timestampable: ~ }
  columns:
    user_id: { type: integer, notnull: true }
    category_id:      { type: integer, notnull: true }

Category:
  actAs: { Timestampable: ~ }
  columns:
    language_id:  { type: integer, notnull: true }
    name: { type: string(255), notnull: true, unique: false }
    revision: { type: integer, notnull: false }
    icon:     { type: string(255) }
  relations:
    User:
       class: User
       local: category_id
       foreign: user_id
       refClass: UserCategory
       type: many

会发生什么:

SQLSTATE[23000]:完整性约束违规:1451 无法删除或更新父行:外键约束失败(testtable.user_category,CONSTRAINT user_category_user_id_user_id FOREIGN KEY (user_id) REFERENCES user (id))

【问题讨论】:

    标签: mysql orm symfony1 doctrine foreign-keys


    【解决方案1】:

    阅读此§ of the doctrine documentation 并在应用程序级级联和数据库级级联之间选择最适合您的解决方案

    【讨论】:

    • 这里没有删除 CASCADE 的选项,只需要删除 user_category 中的条目,而不是类别中的条目。所以更多的是调试 YML 的帮助请求。
    • 哦,我明白了。但是在UserCategory 中定义与User 的关系并使用级联可以完成我猜的工作。
    【解决方案2】:

    您需要在关系上定义级联操作。请参阅Foreign Key's onDelete for dummies 文章(不仅适用于傻瓜),其中包含教义示例。

    【讨论】:

      【解决方案3】:

      greg0ire said 一样,为 UserCategory 定义一个级联就可以了。它完全错过了关系块:

      UserCategory:
        actAs: { Timestampable: ~ }
        columns:
          user_id: { type: integer, notnull: true }
          category_id:      { type: integer, notnull: true }
        relations:
          User: {onDelete: CASCADE, local: user_id, foreign: id, foreignAlias: Users}
          Category: {onDelete: CASCADE, local: category_id, foreign: id, foreignAlias: Categories}
      

      【讨论】:

      • 您正在使用数据库级级联,这是最快的解决方案。 +1
      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2013-04-18
      • 2015-05-07
      • 2016-11-22
      • 2022-01-23
      相关资源
      最近更新 更多