我创建了一个简单的博客,其中包含帖子和评论。我想找到所有至少有一个评论的帖子,并找到所有没有评论的帖子。有没有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 != 0but 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查找所有有评论的帖子
发布评论