Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")})  
like image 301
Dawid Ohia Avatar asked Dec 30 '11 17:12

Dawid Ohia


1 Answers

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") 
like image 178
Inoryy Avatar answered Sep 29 '22 03:09

Inoryy