我想在一个页面中显示所有评论以及所有帖子。例如:我对POST A有3条评论,对B条有2条评论等等。
应该如下所示: POST A - 3评论 POST B - 2评论等
所以为此我编写了这个:
$result = $this->Comment->find('all',array('fields'=>array('Comment.post_id','Comment.comments'),'group'=>'Comment.post_id'));
pr($a);exit;
$this->set('a',$a);
我得到的数组是
Array
(
[0] => Array
(
[Comment] => Array
(
[post_id] => 1
[comments] => Nice Post...Nice Post...Nice Post...
)
)
[1] => Array
(
[Comment] => Array
(
[post_id] => 3
[comments] => wow..nice !!! Lorem Ipsum is simply dummy text of the printing and typesetting
)
)
)
我对post_id = 1
总共有3条评论
我希望这三条评论能够汇集在一起。
答案 0 :(得分:0)
从,'group'=>'Comment.post_id'
find()
答案 1 :(得分:0)
根据您的具体含义,有很多方法可以做到这一点。
问题描述是:
希望显示所有评论以及所有帖子
为此,您只需要在Post上执行查找,包括在结果范围内进行注释。如果您的关联已正确定义,则意味着:
$result = $Post->find('all', array(
'recursive' => 1
));
在这种情况下,$ result的格式为:
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => First article
[content] => aaa
[created] => 2008-05-18 00:00:00
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[post_id] => 1
[author] => Daniel
[email] => dan@example.com
[website] => http://example.com
[comment] => First comment
[created] => 2008-05-18 00:00:00
)
[1] => Array
(
[id] => 2
[post_id] => 1
[author] => Sam
[email] => sam@example.net
[website] => http://example.net
[comment] => Second comment
[created] => 2008-05-18 00:00:00
)
)
)
[1] => Array
(
[Post] => Array
(...
您可以使用the containable behavior来微调返回的信息量,而不是使用递归。
要获取帖子列表及其评论计数,您首先需要了解所需的查询类型 - 例如:
SELECT
Post.id,
COUNT(Comment.id)
FROM
posts as Post
LEFT JOIN
comments as Comment ON (Post.id = Comment.post_id)
GROUP BY
Post.id
如果没有联接,任何没有评论的帖子都不会列出。
有很多方法可以执行这种查询 - 这里是一个:
$result = $Post->find('all', array(
'fields' => array(
'Post.id',
'COUNT(Comment.id)'
),
'group' => array('Post.id'),
'joins' => array(
array(
'table' => 'comments',
'alias' => 'Comment',
'conditions' => array(
'Post.id = Comment.post_id'
)
)
)
));
问题中的群组查询不是正确的结构,除非使用了聚合函数(count,sum等)。要按帖子ID分组所有评论,您可以使用find list:
$result = $Comment->find('list', array(
'fields' => array(
'id',
'comments',
'post_id'
)
));
以这种方式使用响应格式:
$result['post_id']['id']['comment']
即:
array(
1 => array(
aa => 'Nice Post...Nice Post...Nice Post...',
bb => 'Another comment for post id 1'
),
3 => array(
cc => 'wow..nice !!! Lorem Ipsum is simply dummy text of the printing and typesetting ',
dd => 'Another comment for post id 3',
...
)
)