【问题标题】:CodeIgniter - Count rows active record jointCodeIgniter - 计数行活动记录联合
【发布时间】:2015-12-08 18:27:08
【问题描述】:

我正在努力更好地了解 CI 的工作原理。

这是我的第一张桌子,app_news

id / name

我的第二个是app_news_cmets

id / id_news / comment

我用来显示新闻信息的模型是:

public function get_news($where = array()) {
    return $this->db->select('*')
        ->from('app_news')
        ->where($where)
        ->get()
        ->result();
}

我用来计算新闻的 cmets 的模型是:

public function count_comment($id_news) {

    return (int) $this->db->where(array('id_news' => $id_news)
        ->count_all_results('app_news_comments');

}

我的第一个解决方案是在我的视图上打印一个 foreach 并将 count_comment 函数放入循环中以计算我有多少 cmets 但是我不会尊重 MVC 模式。我该怎么做?

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

    获取该信息的最佳方式是使用此查询:

    SELECT 
    app_news.id,
    app_news.name,
    COUNT(app_news_comments.id)
    FROM app_news_comments
    JOIN app_news ON app_news_comments.id_news = app_news.id
    GROUP BY app_news_comments.id_news
    

    因此,您需要使用 Codeigniter 上的 Active Record 创建查询,或者您可以直接添加查询,因为 Codeigniter 上的 Active Record 有一些限制。 但是,您可以在 Codeigniter 上使用这种方式来创建查询:

    $this->db->select('[YOUR FIELDS AND COUNT]', FALSE)
             ->from('app_news_comments') .... etc
    

    并直接添加查询:

    $this->db->query('[QUERY HERE]');
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多