我的表有列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
行。
答案 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 . "'");