PHP:为数组

时间:2017-01-25 09:45:30

标签: php mysql arrays codeigniter

我有2个型号" post_model"和" comment_model"

在Post_controller中的

我从post_model获得了一个包含所有帖子的结果数组。

我试图为每个帖子添加评论数,但我无法帮助。

  • 评论表有post_id。

请让我知道如何处理这个问题。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

试试这个,

int32_t multiple_or_saturate(int32_t a, int32_t b)
{
  if(((a >= 0) && (b >= 0)) || ((a < 0) && (b < 0)))
  {
    if((INT32_MAX / a) >= b)
    {
      return(a * b);
    }
    else
    {
      return(INT32_MAX);
    }
  }
  else
  {
    if((INT32_MIN / a ) <= b)
    {
      return(a * b);
    }
    else
    {
      return(INT32_MIN);
    }
  }
}

希望这能解决您的问题。

答案 1 :(得分:0)

这样的事情会给你每个帖子的评论数量:

some_int = [1..10] # int interval
some_other_int = [1, 2, 3] # int discrete
some_string = ["methodA", "methodB", "methodC"] #discrete

然后,您可以遍历结果集并丰富相应的post对象。 如果您只想为某些特定帖子计算评论,并且您知道他们的post_id,您可以执行以下操作:

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

答案 2 :(得分:-1)

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;