How to delete rows from join-table (ManyToMany) in Doctrine?

走远了吗. 提交于 2021-02-04 14:23:26

问题


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

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 Project\Entity\EntityName

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

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

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

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")}) 

回答1:


To set cascade on doctrine level:

@ORM\ManyToMany(targetEntity="Target", inversedBy="inverse", cascade={"remove", "persist"})

More info: Doctrine2 Annotation Reference.

To set cascade on mysql level:

@ORM\JoinColumn(onDelete="CASCADE", onUpdate="CASCADE")


来源:https://stackoverflow.com/questions/8682088/how-to-delete-rows-from-join-table-manytomany-in-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!