Oth\’s Thoughts


Restrict a record from deletion if it has associated records

Posted in CakePHP by othy on May 30, 2006

ex: Category has Many Article

You don't want to delete a Category if it has related Articles how to do that ?

Well the other way around is possible, you just set 'dependent' to true when you define the association:

$hasMany = array('Article'=>array('dependent'=> true));

now a category is deleted along with all its related articles. beforeDelete is called for every article ( to do some app clean up, ie. delete a dir etc..)

You still want to restrict ?
ok here it is:

if(!$this->Category->Article->hasAny(array('Article.category_id'=> $cat_id)))
{
$this->Category->del($cat_id);
}

Gotchas

This is a good work around, Unfortunetly there are cases where it's useless.
Supose we have another Model Called User.
User hasMany Categories
in the definition of User we've set 'dependent' to true,
which means when we delete a User all its categories will be deleted.
OH NO!! you say ? because those categories might have articles and if they are deleted they will leave orphan childs alone :(.
Tragedy, well not really:

function beforeDelete($id)
{ if(!$this->Article->hasAny(array('Article.category_id'=> $id)))
{
return true;
}
return false;
}

Ahhh I see a smile in your face now baby !
we use Category::beforeDelete so if 'dependent' is to true in any Model that hasMany Categories, thet category won't be deleted and we will save orphan childs, how charitable..Eh..just a last thingy, if the other models that hasMany Categories have exclusive set to true, beforeDelete won't be called.

Well what do you want, Black and White.

One Response to 'Restrict a record from deletion if it has associated records'

Subscribe to comments with RSS or TrackBack to 'Restrict a record from deletion if it has associated records'.


  1. Highly energetic post, I enjoyed tat bit. Will there bbe a
    part 2?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: