In CakePHP I have a model Type and SpecificType.
SpecificType belongTo a Type. (type_id field)
When I delete an entry of SpecificType, how can I also delet
I had the same problem in a situation where I did not want to follow the Cake model key convention.
I set the SpecificType model's belongsTo relationship to Type like so:
public $belongsTo = array(
'Type' => array(
'className' => 'Type',
'foreignKey' => 'type_id',
'conditions' => '',
'fields' => '',
'order' => '',
),
);
Then to get cascading delete to work, I added the following to the 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 that helps someone who has the same problem you had as I'm sure you're not still waiting for an answer.
You want to delete the Type, not the SpecificType. You will also need to make sure you have your model 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 are deleting the child (SpecificType
) and you want to delete it's parent, you must call the delete on the parent model. But keep in mind, if you have the Cascade set up correctly (dependent = true
on the model) all of the SpecificType
children will be deleted anyway.
Note: If you want to delete the parent of the child, you may want to reconsider your relationships and confirm they are correct. If that is really how you want them, then don't do the delete on the child. Simply make sure your cascade relationships are set correctly, pull the child's parent information, and delete the parent. Then all of the children will be removed as well.
I don't think you can delete Type with SpecificType cascade. you can only use cascade if there's hasMany or HABTM relation.
it is said in the manual.
Deletes the record identified by $id. By default, also deletes records dependent on the record specified to be deleted.
For example, when deleting a User record that is tied to many Recipe records (User 'hasMany' or 'hasAndBelongsToMany' Recipes):
* if $cascade is set to true, the related Recipe records are also
deleted if the models dependent-value is set to true. * if $cascade is set to false, the Recipe records will remain after the User has been deleted.
you can always run
$this->del($id, true);
to remove your Type with related SpecificType-s.