Yii delete using multiple active entries

I am after some code advice. I have two models that depend on each other. When one of the models is deleted, I want both records in the database to be deleted.

I process this in one direction using foreign keys, so if the parent is deleted. But since these lines depend on each other, I need the same functionality as the child.

In the child model, I overloaded the delete method to look like this:

public function delete() { $cameraTransaction = $this->dbConnection->beginTransaction(); try { $this->ftpuser->delete(); if($this->beforeDelete()) { $result=$this->deleteByPk($this->getPrimaryKey())>0; $this->afterDelete(); } $cameraTransaction->commit(); } catch(Exception $e) // an exception is raised if a query fails { $cameraTransaction->rollBack(); } } 

I tested and it seems to work well. I was wondering if an expert / guru can confirm whether I did the right thing :)

thanks

Alan

+4
source share
1 answer

I think you are doing everything right. You can do something more general.

Each model has certain relationships, makes some (or all) of the relationships deleted. You must mark them (somehow) delete along with the current record.

I would define a new function besides relations() in the model.

 function deletableRelations() { return array('ftpuser', 'childs', .....); } 

and define some common function (please specify DB transactions in this function.)

 function DeleteRelationships($model) { foreach( $model->deletableRelations() as $relation ) { if( $model->$relation == null) continue; if( is_array($model->$relation)) { foreach( $model->$relation as $relRecord ) { $relRecord->delete(); } } else { $model->$relation->delete(); } } } 

And this versatile feature can be used by any of your models. Make sure that recursion does not occur here (i.e. the parent removes the child ... but the child also tries to remove the parent.)

+2
source

Source: https://habr.com/ru/post/1438657/


All Articles