1
votes

I've got two models Category and Item. Category can have many items and item can be in many categories so relation between them is HABTM. My problem is that a category can be deleted even if items are in it. I have a foreign key in the database table categories_items that RESTRICTS deletion, but it doesn't help. What should I do to prevent category from being deleted if items are in it?

1

1 Answers

1
votes

You need to overwrite the actual "delete" method in your CategoriesController to verify that there are no Items in the category before it is deleted.

Something like...

$c = $this->Category->findById($id);
$rels = $this->CategoriesItem->find('count', array('conditions' => array('CategoriesItem.category_id' => $id)));

if(count($rels) > 0) $this->Session->setFlash("NO WAY JOSE");
else $this->Category->delete($id);