级联删除表的子记录

时间:2013-06-22 08:37:27

标签: yii

我的表有列id,名称和parentid

模型中的关系函数:

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

删除控制器中的操作:

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'));
    }

要求:

此处,如果我使用id = 1删除记录,则还需要删除parentid = 1行。

2 个答案:

答案 0 :(得分:6)

在模型中覆盖beforeDelete方法,在删除父项之前递归删除所有子记录,即

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

确保在事务中包装初始删除调用,以确保删除所有记录或不删除任何记录。

您也可以使用CDbCommand执行删除。

答案 1 :(得分:0)

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'));
    }

或者您也可以通过用户deleteall()删除特定ID

的所有记录
AssociatedModel::model()->deleteAll("parent_id ='" . $id . "'");