qwerty
qwerty

Reputation: 101

Block the possibility of removal if the model has a foreign key

Hi I have model with relation to himself. My relation i can show on this table: enter image description here

This

Rel_Category

is the same that this

Id

.This is the table of category and subcategory. I want to block the possibility of removal if the model has a foreign key. And throw some exception or flash when user want to delete category where it foreign_key in Rel_Category. So if user want to delete test with id=54 then it should display some error that this category have a subcategory and user should first delete this subcategory(id=51 and id=53). UPDATE: In my database i have no action on delete and update enter image description here

Upvotes: 1

Views: 58

Answers (2)

apokryfos
apokryfos

Reputation: 40683

You should define such constraints when you create your database tables:

CREATE TABLE `Category` (         
    ...

    CONSTRAINT `SelfReference` FOREIGN KEY (`Rel_Category`) REFERENCES `Category` (`Id`) ON DELETE RESTRICT ON UPDATE CASCADE
    ....
);

http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

The idea here is that MySQL will maintain your data integrity constraints.

Upvotes: 0

soju
soju

Reputation: 25312

You should handle this in your database, and you could try this in your controller :

if (count($model->smCategories)) {
    Yii::app()->user->setFlash('error', 'This category has sub categories and cannot be deleted.');
} else {
    $model->delete();
}

Upvotes: 1

Related Questions