I am not sure about the question title but tried to explain more below. Thanks in advance for all who helps me.
I sampled the tables to simplify my questions.
DB Tables
- News: news_id, title
- Comments: comment_id, news_id, content, created (timestamp)
Users are posting comments to the news. In a search with the input of "date interval 01.10.2015 - 05.11.2015", the result should include: the news which has been commented between this interval. And comment_count should be shown next to the title on the screen. This comment_count is not whole comment_count, only the count between this dates.
To do that, I ran the query first in comments. Then count comments. Then group by news_id.
$Data = $this->Comment->find('all', array(
'fields' => array(
'News.news_id','News.title'
),
'conditions' => array(
"Comment.created >=" => date('Y-m-d', strtotime("-1 days")) //yesterday's commented news
),
'contain' => array(
'News' => array(
'Comment => array(
'fields' => array('COUNT(Comment.id) as comment_count'),
)
)
),
'group' => array('News.title')
));
The result is below with too much nesting:
Array
(
[0] => Array
(
[News] => Array
(
[id] => 27
[title] => sample news title
[News] => Array
(
[id] => 27
[title] => sample news title
[Comment] => Array
(
[0] => Array
(
[News_id] => 27
[Comment] => Array
(
[0] => Array
(
[Comment_count] => 1
)
)
)
)
)
)
)
)
In conclusion, to reach comment_count, I have to write the nestings manually. However I would like to reach it in the same level with first [title] node.
$JsonData [] = array(
"id" => $Item["News"]["id"],
"title" => $Item["News"]["title"],
"comment_count" => $Item["News"]["News"]["Comment"][0]["Comment"][0]["comment_count"]
);
How can I reduce the life-long nesting?
Thanks in advance.