假设我有以下表格:类别、帖子和类别帖子。类别充当树。Category 和 Post 之间有一个习惯。
我想从帖子控制器做的是找到一个特定的帖子并以线程/嵌套格式列出它所属的类别。
临时解决方案:(我的编码可能很差 - 我很抱歉)
public function view($id=null) {
$this->Post->id = $id;
if($this->Post->exists()) {
$data = $this->Post->read();
$data['Category'] = $this->_thread($data);
$this->set(compact('data'));
}
}
public function _thread($data, $parent_id=null) {
$out = array();
$parents = Set::extract("/Category[parent_id={$parent_id}]", $data);
foreach($parents as $k => $item) {
$out[$k] = $item;
$out[$k]['Category']['children'] = Set::extract("/Category[parent_id={$item['Category']['id']}]", $data);
foreach($out[$k]['Category']['children'] as $key => $child) {
$out[$k]['Category']['children'][$key]['Category']['children'] = $this->_thread($data, $child['Category']['id']);
}
}
return $out;
}