簡體   English   中英

PHP:為數組中的每個帖子添加評論計數

[英]PHP: add Comments Count for each Post in array

我有 2 個模型“post_model”和“comment_model”

在 Post_controller 中,我從 post_model 得到一個包含所有帖子的結果數組。

我正在嘗試為每個帖子添加評論數,但我不能也需要幫助。

  • 評論表有 post_id。

請讓我知道如何處理這個問題。 提前致謝。

嘗試這個,

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

希望這能解決您的問題。

這樣的事情應該給你每個帖子的評論數量:

SELECT 
COUNT(*) AS comment_cnt, post_id 
FROM comment_table 
GROUP BY post_id;

然后就可以遍歷結果集,豐富對應的post對象。 如果您只想計算某些特定帖子的評論並且您知道他們的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM