cakephp查找所有有评论的帖子

编程入门 行业动态 更新时间:2024-10-27 10:22:17
本文介绍了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查找所有有评论的帖子

本文发布于:2023-10-23 08:20:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520297.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:帖子   cakephp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!