0
votes

I have a table called custom_carts and I have a table called custom_cart_items.

custom_cart_items has a foreign key called custom_cart_id that is set to custom_cart.id

According to the Cake Manual, when you call Model->delete() the first param is the id of the entry you want to delete and the second param is whether or not to cascade delete the dependent entries.

So when I call $this->CustomCart->delete(7,true) I get this error:

SQL Error: 1451: Cannot delete or update a parent row: a foreign key constraint fails (`krake`.`custom_cart_items`, CONSTRAINT `custom_cart_items_ibfk_1` FOREIGN KEY (`custom_cart_id`) REFERENCES `custom_carts` (`id`))

Here is the query:

DELETE `CustomCart` 
FROM `custom_carts` AS `CustomCart` 
LEFT JOIN `users` AS `User` 
ON (`CustomCart`.`user_id` = `User`.`id`)  
WHERE `CustomCart`.`id` = 25 

Shouldn't it cascade and dlete the other entry too?

So why am I getting an error?

3
what are you associations? Also - true is the default, so you can remove that. - Dave
also - you're not manually specifying the foreign keys are you? you shouldn't need to. - Dave
@Dave I am not sure what you are asking. I set up the association by running this query: ALTER TABLE custom_cart_items ADD FOREIGN KEY (custom_cart_id) REFERENCES custom_cart(id); - JD Isaacks
What is your custom_cart_id field - INT 11? Can you list out a few of the important fields of each of your tables, and the associations you have for each? (by editing the question - this will help potential other answerers w/ your question too) - Dave
Could you show the query that CakePHP is executing? - Adam Prax

3 Answers

5
votes

You must set the dependent parameter to true in the model with the hasmany relationship in order to enable cascading deletion.

Your model would look something like this:

class CustomCart extends AppModel {
         var $name = 'CustomCart';
         var $hasMany = array(
         'CustomCartItem' => array(
             'dependent'=> true
         )
);
}

Please see http://book.cakephp.org/view/82/hasMany

0
votes

Just adding fields to a table (regardless of the field name) does not tell CakePHP that they're associated, nor does it link them for cascading deletion.

You need to set the associations in your model: SEE DETAILS HERE.

0
votes

On the other hand, if you want to delete a record from a table A, and there is another table B which as a FOREIGN KEY constraint on table A, you must set the option on that foreign key of the table B in the Database like this "SET NULL ON DELETE".

I usually do this in MySqlWorkbench, but you can also use legacy SQL queries to create a table with such an option.