Cakephp在一个页面中显示帖子的所有评论
我想在一个页面中显示所有评论以及所有帖子。例如:我对帖子a有3条评论,对帖子B有2条评论,依此类推 应该是这样的: 发表A-3评论 发表B-2评论等等 为此,我编写了以下代码:Cakephp在一个页面中显示帖子的所有评论,php,cakephp-2.0,Php,Cakephp 2.0,我想在一个页面中显示所有评论以及所有帖子。例如:我对帖子a有3条评论,对帖子B有2条评论,依此类推 应该是这样的: 发表A-3评论 发表B-2评论等等 为此,我编写了以下代码: $result = $this->Comment->find('all',array('fields'=>array('Comment.post_id','Comment.comments'),'group'=>'Comment.post_id')); pr($a);exit; $th
$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条评论
我想把这三条评论放在一起。删除,'group'=>'Comment.post_id'从你的发现中删除。根据你的确切意思,有很多方法可以做到这一点 邮购 问题说明如下: 要显示所有评论以及所有帖子吗 为此,您只需要在Post上执行查找,包括结果范围内的注释。如果您的关联定义正确,则意味着:
$result = $Post->find('all', array(
'recursive' => 1
));
在这种情况下,$结果将采用以下形式:
[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
(...
您可以使用来微调返回的信息量,而不是使用递归
查找统计后的评论
要获取帖子列表及其评论数量,您首先需要了解所需的查询类型,例如:
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对所有评论进行分组,您可以使用:
以这种方式使用的响应格式为:
$result['post_id']['id']['comment']
i、 e:
这是对的,但我想要的是数字,例如,总共1篇,3篇,等等,并添加了一个回复帖子和评论计数的例子。
$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',
...
)
)