0

Lets say I have the following tables: categories, posts and categories_posts. Category acts as a Tree. There is a habtm between Category and Post.

What I want to do from the Posts Controller is find a specific Post and list the Categories it belongs to in a threaded/nested format.

temporary solution: (my coding is probably rather poor - my apologies)

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;
}
ryan
  • 33
  • 1
  • 7
  • Right now, I have a method called _thread that is threading the data, my code isn't that great... :s basically after I find the posts i have $data = $this->_thread($data, $parent=null); and that recursively treads the data from the find... – ryan Aug 28 '12 at 15:27
  • Please describe table structure and represent the form in which you need the data (sample look). – Krishna Aug 29 '12 at 07:46

1 Answers1

0

This may help you out :

$data = $this->Post->find('threaded', array(
    'conditions' => array('id' => 1)
));

'conditions' array is for example,you can pass your required conditions if any.

Bonz
  • 1
  • 2