MySQL 如何从 Doctrine 中的连接表 (ManyToMany) 中删除行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8682088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete rows from join-table (ManyToMany) in Doctrine?
提问by Dawid Ohia
I have a join-table which is created by using @ORM\ManyToMany
annotation in Symfony2/Doctrine.
It joins Category
and Parameter
table.
我有一个连接表,它是通过@ORM\ManyToMany
在 Symfony2/Doctrine 中使用注释创建的。它连接Category
和Parameter
表。
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:
现在我想从参数表中删除所有参数。因为在连接表上定义了外键约束,所以我不能只从参数表中删除行。首先,我必须从连接表中删除子行。但是 Dotrine 的 DQL 语法需要给出实体的名称,例如:
DELETE Project\Entity\EntityName
But what is the name of the join-table entity generated by using ManyToMany association? How to deal with it?
但是使用 ManyToMany 关联生成的连接表实体的名称是什么?如何处理?
Alternately, how can I set ON UPDATE CASCADE and ON DELETE CASCADE on foreign key constraints in join-table defined by @ORM\ManyToMany
annotation.
或者,如何在@ORM\ManyToMany
注释定义的连接表中的外键约束上设置 ON UPDATE CASCADE 和 ON DELETE CASCADE 。
EDIT:
编辑:
join-table schema:
连接表架构:
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 UPDATE
and on DELETE
by default are set to RESTRICT
on UPDATE
并且on DELETE
默认设置为RESTRICT
THE FINAL SOLUTION WOULD BE:
最终的解决方案是:
* @ORM\ManyToMany(targetEntity="CategoryParam", cascade={"persist","remove"})
* @ORM\JoinTable(name="categories_params",
* joinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="param_id", referencedColumnName="id", onDelete="CASCADE")})
回答by Inoryy
To set cascade on doctrine level:
在学说级别设置级联:
@ORM\ManyToMany(targetEntity="Target", inversedBy="inverse", cascade={"remove", "persist"})
More info: Doctrine2 Annotation Reference.
更多信息:Doctrine2 注释参考。
To set cascade on mysql level:
在 mysql 级别设置级联:
@ORM\JoinColumn(onDelete="CASCADE", onUpdate="CASCADE")