cakephp删除线程记录

时间:2012-05-11 06:24:50

标签: cakephp

我使用CakePHP及其find('threaded')功能在我的某个网站中实现了评论功能。

当我删除父评论时,我希望使用CakePHP模型的删除方法删除它的所有子评论(n级孩子)。

说,以下是这种情况:

id = 5 parent_id = 0;
id = 6 parent_id = 5;
id = 7 parent_id = 5;
id = 8 parent_id = 7 ;

我做了:

$this->Comment->id = 5;
$this->Comment->delete();

我想要将评论ID = 5,6,7,8的记录删除。

请指教。
感谢

2 个答案:

答案 0 :(得分:1)

我没有测试过以下代码,但我会做这样的事情:

<?php
class Comment extends AppModel {
    public function afterDelete() {
        $this->deleteChildren($this->id);
    }

    private function deleteChildren($parentId) {
        $children = $this->findByParentId($parentId);
        if (!empty($children)) {
            foreach ($children as $child) {
                $this->deleteChildren($child['Comment']['id']);
                $this->delete($child['Comment']['id']);
            }
        }
    }
}
?>

答案 1 :(得分:0)

@ greew上面的回答中的小修正,对我来说就像下面一样:

public function afterDelete() {
     $this->__deleteChildren($this->id);
}

private function __deleteChildren($parentId) {
   $children = $this->findAllByParentId($parentId);
   if (!empty($children)) {
        foreach ($children as $child) {
           $this->delete($child['Comment']['id']);
        }
    }
}

非常感谢你!