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
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.
This of course only works if you have your model relationships set up in your comment.php model.