1

I have this query can someone help me transfer it to codeigniter style in model.

SELECT
    a.*, 
    (
        SELECT COUNT(*) FROM `comment` c 
        WHERE c.comment_article_id = a.`News_News_ID`
    ) AS counta
FROM
    `news_news` a

Update: I try this and it work nicely but im not sure it is good practice

     $sql="SELECT a.*,
     ( SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.`News_News_ID` ) as counta
     FROM `news_news` a";
 $query = $this->db->query($sql, array('News_Cate_ID' => $cate), $start, $display);
Nam Hao
  • 67
  • 2
  • 9
  • `CI` allow you to write your custom `sql` but it always a good practice to use standard model way like http://stackoverflow.com/questions/6047149/subquery-in-codeigniter-active-record – urfusion Apr 13 '16 at 11:55

2 Answers2

0

Use join instead of sub query and according to your query you didn't need where condition while using joins

$this->db->select('a.*,COUNT(c.*) AS counta');
$this->db->from('news_news AS a');
$this->db->join('comment AS c', 'c.comment_article_id = a.News_News_ID');
$query = $this->db->get();

For more information

urfusion
  • 5,528
  • 5
  • 50
  • 87
0

Try below code. This query will return each article with comment count

$this->db->select('a.*,COUNT(c.*) AS count');
$this->db->from('news_news a');
$this->db->join('comment c', 'a.News_News_ID = c.comment_article_id ','LEFT');
$this->db->group_by('a.News_News_ID')
$query = $this->db->get();
Vinie
  • 2,983
  • 1
  • 18
  • 29