0

我已经使用 CakePHP 和它的特性在我的一个站点中实现了评论功能find('threaded')

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

说,以下是这种情况:

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 的记录。

请指教。
谢谢

4

2 回答 2

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']);
            }
        }
    }
}
?>
于 2012-05-11T06:37:00.703 回答
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']);
        }
    }
}

非常感谢绿!

于 2012-05-11T09:41:01.277 回答