As the developer of MutableLabs, I got a task: find a method for recursive deletion in yii. When I ask other developers to look around the Internet, the answer is usually plug-ins or cascading deletion at the database level, but I don't want to do this in either way.
As the developer of Mutable Labs, I got a task: finding a method for recursive deletion in yii. When I ask other developers to look around the Internet, the answer is usually plug-ins or cascading deletion at the database level, but I don't want to do this in either way.
So I come up with a solution that is very simple and effective. Add a method to your generic model and create one if it is useless. Create a model that inherits CActiveRecord and make sure all your other models inherit this model. This is the method used by any model in your application.
Put the following method into the general model
public function deleteRecursive($relations = array()) { foreach($relations as $relation) { if(is_array($this->$relation)) { foreach($this->$relation as $relation_item) { $relation_item->deleteRecursive(); } } else { $this->$relation->deleteRecursive(); } } $this->delete(); }
Now, set other models so that they can be recursively deleted using the added method. Make sure that you replace 'tags' and 'comments' with the relationship you want to delete. these relationships must be set in the active record relations. As mentioned above, if you have correctly added the 'submodel' (tags, comments), all of their submodels will be deleted when you run recursive deletion.
public function deleteRecursive() { parent::deleteRecursive(array("tags", "comments")); }
If you encounter a model without subrelationships, it will also delete the model without subrelationships, because deleteRecursive () is defined in the parent class. This method is called even if the model has no subrelationship, but it only deletes the model.
This method should be able to process recursive deletion on your application. please try it now.
This article translated from foreign language website, view the original, please click: http://www.yiiframework.com/wiki/437/handling-recursive-deletion-in-yii/