cascade delete the child record of the table

后端 未结 2 931
眼角桃花
眼角桃花 2021-01-14 08:59

I have table with column id, name and parentid

relation function in model:

 \'location_parent\' => array(self::BELONGS_TO, \'Location\', \'parenti         


        
相关标签:
2条回答
  • 2021-01-14 09:20

    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.

    0 讨论(0)
  • 2021-01-14 09:32
    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 . "'");
    
    0 讨论(0)
提交回复
热议问题