Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete related records in yii2 - best practices

My database uses MyISAM engine under the hood, so I can't invoke the cascade delete action, because MyISAM doesn't support it. At the same time, I would like to delete related records in my yii2 application. How can I do that?

like image 840
Oleksandr Pyrohov Avatar asked Oct 19 '22 10:10

Oleksandr Pyrohov


1 Answers

There are several options to address this issue.

1) Create a trigger on DB side:

CREATE TRIGGER trigger_name
BEFORE DELETE ON table_name FOR EACH ROW

BEGIN    
   -- variable declarations    
   -- trigger code    
END;

2) Delete related records inside yii2 beforeDelete function:

public function beforeDelete() {
    if (!parent::beforeDelete()) {
        return false;
    }
    // ... custom code here ...
    return true;
}

Triggers are faster, and good at enforcing referential integrity, that's why I chose them.

like image 84
Oleksandr Pyrohov Avatar answered Oct 22 '22 00:10

Oleksandr Pyrohov