cascade delete the child record of the table

2020-03-26 05:01发布

问题:

I have table with column id, name and parentid

relation function in model:

 'location_parent' => array(self::BELONGS_TO, 'Location', 'parentid'),
 'location_children' => array(self::HAS_MANY, 'Location', 'parentid', 'order' => 'id ASC'),

delete action in controller:

public function actionDelete($id)
    {
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

Requirement:

Here, If I delete the record with id = 1, then the row with parentid = 1 is also required to delete.

回答1:

In your model override the beforeDelete method to delete all child records recursively before deleting the parent i.e.

public function beforeDelete(){
    foreach($this->location_children as $c)
        $c->delete();
    return parent::beforeDelete();
}

Be sure to wrap the initial delete call in a transaction to ensure all or none of the records are deleted.

You could also just use CDbCommand to perform the deletion.



回答2:

public function actionDelete($id)
    {
              //delete location _children 

 foreach( $this->loadModel($id)->location_children as $c)
         $c->delete();

              //delete location_parent

 foreach( $this->loadModel($id)->location_parent as $c)
         $c->delete();

            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

or you can also user deleteall() to delete all records of specific id

AssociatedModel::model()->deleteAll("parent_id ='" . $id . "'");


标签: yii