CakePHP - delete cascade not working

In CakePHP, I have a model type and a SpecificType.

SpecificType belongs to the type. (type_id field)

When I delete a SpecificType entry, how can I also delete Type?

I have it like

$this->SpecificType->del($id, true) 

However, the entry in the Type section is not deleted.

Thanks,
Tee

+3
source share
3 answers

I don’t think you can remove Type with the SpecificType cascade. You can only use the cascade if there is a hasMany or HABTM relationship.

the manual says.

Deletes the entry identified by $ id. By default, entries are also deleted, depending on the entry specified for deletion.

For example, when deleting a user, a record bound to many record recipes (User 'hasMany' or 'hasAndBelongsToMany' Recipes):

 * if $cascade is set to true, the related Recipe records are also 

deleted if dependent model values ​​are set to true. * If the $ cascade parameter is set to false, the recipe entries will remain after the User has been deleted.

you can always run

 $this->del($id, true); 

to remove your type with associated SpecificType-s.

+8
source

You want to remove Type, not SpecificType. You also need to make sure your model is set correctly for Type:

 var $hasMany = array( 'SpecificType' => array( 'className' => 'SpecificType', 'foreignKey' => 'type_id', 'dependent'=> true, ) ); 

Then delete the type and it will work.

If you delete a child ( SpecificType ) and want to remove it as a parent, you must call delete in the parent model. But keep in mind, if you configured Cascade correctly ( dependent = true on the model), all SpecificType children will be deleted anyway.

Note. If you want to remove the parent of a child, you can review your relationships and confirm that they are true. If this is really the way you want, do not delete on the child. Just make sure your cascading relationship is set up correctly, pull out the child parent information and remove the parent. Then all children will be removed.

+8
source

I had the same problem in a situation where I did not want to follow the Cake Model Contract .

I set the type to SpecificType to relate to the type, for example:

 public $belongsTo = array( 'Type' => array( 'className' => 'Type', 'foreignKey' => 'type_id', 'conditions' => '', 'fields' => '', 'order' => '', ), ); 

Then, to make cascading deletion work, I added the following SpecificType model:

 public function beforeDelete($cascade) { // Make sure the parent method runs. $continue = parent::beforeDelete($cascade); if ($continue) { // Delete the Type if there is one. $typeId = $this->field('type_id'); if (!empty($typeId)) { $continue = $this->Type->delete($typeId); } } return $continue; } 

I hope this helps someone who has the same problem as you, as I am sure that you have not yet waited for an answer.

+2
source

Source: https://habr.com/ru/post/1247457/


All Articles