cakephp查找所有有评论的帖子 [英] cakephp find all posts that have comments

查看:97
本文介绍了cakephp查找所有有评论的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的博客,其中包含帖子和评论。我想找到所有至少有一个评论的帖子,并找到所有没有评论的帖子。有没有cakephp的方式来做到这一点? I.E.也许像

  $ this-> Post-> find('all',???) 

我最后写了我自己的查询,下面的示例查找所有至少有1条评论的帖子

  SELECT * 
FROM(
select posts。*,count(comments.id)as comment_count
从帖子离开posts.id = comments.post_id
组by posts.id
)作为T
WHERE comment_count!= 0



但似乎有更好的方法。



注意: a post有多个评论和评论belongsTo Post

解决方案

  $ grouped_comments = $ this-& Comment-> find('all',array('group'=>'Comment.post_id')); 

这将给你一个由post_id分组的所有注释的数组,帖子,这是你想要的。



假设您想发布包含评论的所有帖子标题的列表。

  echo< H1>帖子包含评论:< / H1>; 
foreach($ grouped_comments as $ comment){
echo $ comment ['Post'] ['Title']。 < br>;
}

这当然仅适用于您在注释中设置的模型关系.php模型。


I created a simple blog that has posts and comments. I want to find all the posts that have at least one comment and also find all the posts with no comments. Is there a cakephp way to do this? I.E. maybe something like

$this->Post->find('all', ???);

I ended up writing my own query, the example below finds all the posts with at least 1 comment

SELECT *
  FROM (
       select posts.*, count(comments.id) as comment_count
        from posts left join comments on posts.id = comments.post_id
        group by posts.id
       ) as T
 WHERE comment_count != 0

but there seems like there would be a better way to do this.

Note: a Post hasMany Comment and Comment belongsTo Post

解决方案

$grouped_comments = $this->Comment->find('all', array('group' => 'Comment.post_id'));

This will give you an array of all Comments grouped by post_id so you will have exactly one comment for each post, which is what you want. From there you can do whatever you want with that data.

Let's say you wanted to post a list of all post titles with comments.

echo "<H1>Posts with comments:</H1>";
foreach ($grouped_comments as $comment) {
echo $comment['Post']['Title'] . "<br>";
}

This of course only works if you have your model relationships set up in your comment.php model.

这篇关于cakephp查找所有有评论的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆