简体   繁体   中英

PHP: add Comments Count for each Post in array

I have 2 models "post_model" and "comment_model"

in Post_controller I get a result array from post_model which has all the posts.

I'm trying to add comments count for each post but I couldn't and need help.

  • comment table has post_id.

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. If you want to count comments only for some specific posts and you know their post_id, you could do something like:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM