O Connor
O Connor

Reputation: 4392

Yii Framework 2.0 prevent deleting any record whom id is being used as a foreign key

I have a relational database which id of records in one table is being used as a foreign key in other relational tables. I have a delete operation. Of course I want to prevent deleting any record whom id is being used as a foreign key in another table. My solution is to find the record in all relational tables one by one by the id of the record that I want to delete. If nothing is found at all, it is allowed to be deleted. But this solution is not efficient since you need to find record in all relational tables one by one.

Of course MySQL has some relational restriction such as ON DELETE RESTRICT or NO ACTION. But then when I delete a record whom id is being used in another table, I get the error message with some source code which I do not want to show. I have tried to use try catch as following but it does not work.

$model= $this->findModel($id);
try {
     $model->delete();
} catch(Exception $e) {
     throw new \yii\web\ForbiddenHttpException('Could not delete this record.' . $e);
}

But try catch does not work for me. Is that any other solution to check if the id of a record is being used in anther relational table? I am working with Yii framework 2.0

Upvotes: 1

Views: 1373

Answers (1)

soju
soju

Reputation: 25312

You should simply catch IntegrityException :

$model= $this->findModel($id);
try {
     $model->delete();
} catch(\yii\db\IntegrityException $e) {
     throw new \yii\web\ForbiddenHttpException('Could not delete this record.' . $e);
}

Upvotes: 3

Related Questions