[英]PHP: add Comments Count for each Post in array
I have 2 models "post_model" and "comment_model"我有 2 个模型“post_model”和“comment_model”
in Post_controller I get a result array from post_model which has all the posts.在 Post_controller 中,我从 post_model 得到一个包含所有帖子的结果数组。
I'm trying to add comments count for each post but I couldn't and need help.我正在尝试为每个帖子添加评论数,但我不能也需要帮助。
Please let me know how to handle this.请让我知道如何处理这个问题。 Thanks in advance.提前致谢。
Try this,尝试这个,
SELECT
p.post_id,
(SELECT count(c.post_id) FROM comments c WHERE c.post_id = p.post_id) cnt
FROM posts p
GROUP BY p.post_id LIMIT 5
Hope this will solve your problem.希望这能解决您的问题。
Something like this should give you the number of comments for each post:这样的事情应该给你每个帖子的评论数量:
SELECT
COUNT(*) AS comment_cnt, post_id
FROM comment_table
GROUP BY post_id;
Then you can traverse the result set and enrich the corresponding post objects.然后就可以遍历结果集,丰富对应的post对象。 If you want to count comments only for some specific posts and you know their post_id, you could do something like:如果您只想计算某些特定帖子的评论并且您知道他们的 post_id,您可以执行以下操作:
SELECT
COUNT(*) AS comment_cnt, post_id
FROM comment_table
WHERE post_id IN (post_id1, post_id2, ...)
GROUP BY post_id;
SELECT p.post_id, p.post_title, p.post_content, p.user_id,count(c.post_id)
FROM posts p
LEFT JOIN comments c USING(post_id)
GROUP BY p.post_id, p.post_title, p.post_content, p.user_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.