级联删除表的子记录 [英] cascade delete the child record of the table

查看:38
本文介绍了级联删除表的子记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含列 id、name 和 parentid 的表

I have table with column id, name and 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的行也需要删除.

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

推荐答案

在您的模型中重写 beforeDelete 方法以在删除父记录之前递归删除所有子记录,即

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.

您也可以使用 CDbCommand 来执行删除操作.

You could also just use CDbCommand to perform the deletion.

这篇关于级联删除表的子记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆