【问题标题】:Doctrine One-To-One bidirectional relationship CASCADE directionDoctrine One-To-One 双向关系 CASCADE 方向
【发布时间】:2016-10-27 08:27:08
【问题描述】:

我有两个使用 yaml 注释定义的学说实体(User 和 DatiFiscali),如下所示。

我想要实现的是在删除 User 以同时在级联上删除 DatiFiscali 时,

但是使用下面的配置我只能获得相反的行为:删除 DatiFiscali 时,User 也将在级联时被删除。

我可以通过手动添加以下外键轻松获得想要的结果:

CONSTRAINT `datifiscali_ibfk_1` FOREIGN KEY (`id`) REFERENCES `User` (`datifiscali_id`) ON DELETE CASCADE

但是,当使用 'docrine orm:schema-tool:update' 正确地更新架构时,学说会尝试删除上面的外键。

如果没有:

  • 改变关系方向。
  • 必须使用自定义 sql 而不是依赖于 orm:schema-tool:create 教义

实体 A:

Test\User:
    type: entity
    table: User
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
    fields:
        username:
            type: text
            nullable: true
        email:
            type: text
            nullable: true

    oneToOne:
        datiFiscali:
            targetEntity: DatiFiscali
            inversedBy: user
            joinColumns:
                datifiscali_id:
                    referencedColumnName: id
                    onDelete: CASCADE

实体 B:

Test\DatiFiscali:
    type: entity
    table: DatiFiscali
    id:
        id:
            type: integer
            generator:
                strategy: AUTO

    fields:
        name:
            type: text
            nullable: true
        surname:
            type: text
            nullable: true
        business_name:
            type: text
            nullable: true

    oneToOne:
        user:
            targetEntity: User
            mappedBy: datiFiscali

感谢您的帮助!

【问题讨论】:

  • 试试cascade: [remove]。但我不确定在这种情况下应该在哪一侧定义。可能在DatiFiscali。更多信息:docs.doctrine-project.org/projects/doctrine-orm/en/latest/…
  • 感谢@dragoste 的建议,令人惊讶的是,我在两个文件中都尝试了 cascade: [remove],但没有任何结果:在 orm 级别上不会发生级联删除。
  • @Davide 您需要在您的班级DatiFiscali 的属性用户上指定onDelete: CASCADE。就像现在一样,您说“在删除 DatiFiscali 时请删除用户”,但您想说“在删除用户时,请删除 DatiFiscali ”
  • 好的,当定义“mappedBy”属性时,我显然也在 oneToOne 关系中尝试过这个,任何“joinColumn”属性都会被忽略。通过评论 mappedBy 而不是学说提出以下更改:
  • ALTER TABLE DatiFiscali ADD user_id INT DEFAULT NULL; ALTER TABLE DatiFiscali ADD CONSTRAINT FK_7A2A1DE5A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE; CREATE UNIQUE INDEX UNIQ_7A2A1DE5A76ED395 ON DatiFiscali (user_id); 这意味着架构现在将有一个额外的 'user_id' 列(同一关系的双索引)。

标签: php symfony doctrine-orm annotations doctrine


【解决方案1】:

尝试将级联选项放在正确的位置:

oneToOne:
    datiFiscali:
        targetEntity: DatiFiscali
        inversedBy: user
        joinColumns:
            datifiscali_id:
                referencedColumnName: id
        cascade: ["remove"]

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多