2011-07-14 52 views
1

我想为我的新闻报道页面的嵌套查询提供一些帮助 - 基本上我希望每篇文章都有相关的评论显示在下面,但目前只对每篇文章返回一条评论:(从两张桌子上拉取信息

function get_records($limit, $offset, $sort) { 
    $this->db->select('news.*, COUNT(comments.news_id) as comments, comments.comment as comment, news.id as id, news.created_on as created_on, CONCAT(users.firstname, " ", users.surname) as author, categories.category as category, news_types.type as news_type', FALSE); 
    $this->db->from('news', 'comments'); 
    $this->db->join('users', 'users.id = news.author', 'left'); 
    $this->db->join('comments', 'comments.news_id = news.id', 'left'); 
    $this->db->join('categories', 'categories.id = news.category', 'left'); 
    $this->db->join('news_types', 'news_types.id = news.news_type', 'left'); 
    $this->db->group_by('news.id'); 
    $this->db->order_by('news.id', 'DESC'); 
    $this->db->limit($limit, $offset); 
    $query = $this->db->get(); 
    if($query->num_rows() > 0) { 
     return $query->result_array(); 
    } 
} 

回答

3
$this->db->group_by('news.id'); 

GROUP BY将每则新闻只返回一个记录到你,这就是为什么你只能得到一个评论。你需要有第二个查询获取所有的评论或删除GROUP BY获得所有与冗余新闻项目信息的评论(这真的不是一个好主意)。

2

下面是你想要做的 - 理论上,不是代码:

你会想制作一大堆新闻报道,数组中的一个项目是匹配注释的另一个数组。

  1. 将所有新闻报道收集在一个查询中。
  2. 循环播放新闻报道,并循环播放,运行另一个查询,以抓取符合新闻故事的评论。
  3. 将注释转储到数组中,并将该数组作为对象属性附加到result()项目,或者将result_array()附加为每个数组的新项目。

然后从模型中将全新的数组/对象返回到控制器。

;)

相关问题