I have created a RESTful PHP web service using Lithium which contains comments, each comment can have a parent comment allowing comments to be infinitely recursive.
I have set up the relationship within my model using the correct key.
My data is currently formatted list this (using Model::()
):
Array
(
[1C19FA9D-0432-A382-5236-2C59E0967F58] => Array
(
[id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] =>
[user_id] => 4
[comment] => This is a test
[created] => 2012-03-16 16:41:33
[updated] =>
)
[3B2350BA-9BA7-D7D4-2ED4-42BD40BC1AF0] => Array
(
[id] => 3B2350BA-9BA7-D7D4-2ED4-42BD40BC1AF0
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[user_id] => 543
[comment] => Testing
[created] => 2012-03-16 17:25:47
[updated] =>
)
[4CFD2D8B-D05F-7C8A-E2A9-38D5677280A9] => Array
(
[id] => 4CFD2D8B-D05F-7C8A-E2A9-38D5677280A9
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[user_id] => 53
[comment] => A Test
[created] => 2012-03-16 17:25:38
[updated] =>
)
)
And I would prefer it was formatted like this
Array
(
[0] => Array
(
[id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] =>
[user_id] => 4
[comment] => This is a test
[created] => 2012-03-16 16:41:33
[updated] =>
[comment] => Array(
[0] => Array
(
[id] => 3B2350BA-9BA7-D7D4-2ED4-42BD40BC1AF0
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[user_id] => 543
[comment] => Testing
[created] => 2012-03-16 17:25:47
[updated] =>
)
[1] => Array
(
[id] => 3B2350BA-9BA7-D7D4-2ED4-42BD40BC1AF0
[page_id] => 0384F94C-8B99-F692-62D0-7B24B0885257
[parent_id] => 1C19FA9D-0432-A382-5236-2C59E0967F58
[user_id] => 543
[comment] => A Test
[created] => 2012-03-16 17:25:47
[updated] =>
)
)
)
)
Is there a recursing function built in to Lithium or is this something I would have to create myself? Please also note the changes in Keys.
To fix this I actually ended up generating my own array from the results as follows:
public function index($page_id) {
$page = Pages::first($page_id);
$site = Sites::first($page->site_id);
$comments = Comments::all(array('conditions' => array('page_id' => $page->id, 'comment_id' => NULL)));
if ($this->request->type == 'JSON')
$comments = $this->_recursiveComments($comments, $page);
return compact('comments', 'page', 'site');
}
protected function _recursiveComments($comments, $page) {
foreach($comments as $c) {
$children = Comments::all(array('conditions' => array('comment_id' => $c->id)));
$c->children = $children;
$this->_recursiveComments($children, $page);
}
return $comments;
}
That way I could just do a foreach($comments as $key => $value)
loop and avoid the random keys.