如何从 Doctrine 中的连接表 (ManyToMany) 中删除行?

2022-01-03 00:00:00 mysql symfony doctrine-orm

我有一个连接表,它是通过在 Symfony2/Doctrine 中使用 @ORMManyToMany 注释创建的.它连接CategoryParameter 表.

I have a join-table which is created by using @ORMManyToMany annotation in Symfony2/Doctrine. It joins Category and Parameter table.

现在我想从参数表中删除所有参数.因为在连接表上定义了外键约束,所以我不能只从参数表中删除行.首先,我必须从连接表中删除子行.但是 Dotrine 的 DQL 语法需要给出实体的名称,例如:

Now I want to delete all parameters from the Parameter table. Because there are foreign key constraints defined on join-table I can't just delete rows from Parameter table. First I have to delete child rows from join-table. But Dotrine's DQL syntax require to give a name of the entity, like:

DELETE ProjectEntityEntityName

但是使用 ManyToMany 关联生成的连接表实体的名称是什么?怎么处理?

But what is the name of the join-table entity generated by using ManyToMany association? How to deal with it?

或者,如何在由 @ORMManyToMany 注释定义的连接表中的外键约束上设置 ON UPDATE CASCADE 和 ON DELETE CASCADE.

Alternately, how can I set ON UPDATE CASCADE and ON DELETE CASCADE on foreign key constraints in join-table defined by @ORMManyToMany annotation.

连接表架构:

CREATE TABLE `categories_params` (
    `category_id` INT(11) NOT NULL,
    `param_id` INT(11) NOT NULL,
    PRIMARY KEY (`category_id`, `param_id`),
    INDEX `IDX_87A730CB12469DE2` (`category_id`),
    INDEX `IDX_87A730CB5647C863` (`param_id`),
    CONSTRAINT `categories_params_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `allegro_category` (`id`),
    CONSTRAINT `categories_params_ibfk_2` FOREIGN KEY (`param_id`) REFERENCES `category_param` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

on UPDATEon DELETE 默认设置为 RESTRICT

最终的解决方案是:

 * @ORMManyToMany(targetEntity="CategoryParam", cascade={"persist","remove"})
 * @ORMJoinTable(name="categories_params",
 *      joinColumns={@ORMJoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE")},
 *      inverseJoinColumns={@ORMJoinColumn(name="param_id", referencedColumnName="id", onDelete="CASCADE")}) 

推荐答案

在学说级别设置级联:

@ORMManyToMany(targetEntity="Target", inversedBy="inverse", cascade={"remove", "persist"})

更多信息:Doctrine2 注释参考.

在mysql级别设置级联:

To set cascade on mysql level:

@ORMJoinColumn(onDelete="CASCADE", onUpdate="CASCADE")

相关文章