In some of my projects I had a requirement to prevent deletion of the records, which had children. That’s why I create a small behaviour which checks these cases and prevent this.
Add this code in /app/models/behaviours/has_children.php
/**
* Prevent deletion if child record found
*
* @author Nik Chankov
* @url http://nik.chankov.net
*/
class HasChildrenBehavior extends ModelBehavior {
/**
* Empty Setup Function
*/
function setup(&$model) {
$this->model = $model;
}
/**
* Run the check and cancel the deletion if child is found
* @access public
*/
function beforeDelete(){
if(isset($this->model->hasMany)){
foreach($this->model->hasMany as $key=>$value){
$childRecords = $this->model->{$key}->find('count', array('conditions'=>array($value['foreignKey']=>$this->model->id)));
if($childRecords > 0){
return false;
}
}
}
//Checking habtm relation as well, thanks to Zoltan
if(isset($this->model->hasAndBelongsToMany)){
foreach($this->model->hasAndBelongsToMany as $key=>$value){
$childRecords = $this->model->{$key}->find('count', array('conditions'=>array($value['foreignKey']=>$this->model->id)));
if($childRecords > 0){
return false;
}
}
}
return true;
}
}
?>