Codeigniter Active Record中的多个Select Count SQL查询

时间:2013-06-22 12:58:05

标签: php mysql codeigniter

我喜欢将以下MySQL查询转换为Codeigniter Active Record Queries。

以下是MySQL:

select brand_id,name,(select count(*) from items where brand_id = b.brand_id) as itemc, (select count(*) from models where brand_id = b.brand_id) as modelc from brands as b

Codeigniter:

$this->db->limit($perpage,$page);
    $query = 'select brand_id,name,(select count(*) from items where brand_id = b.brand_id) as itemc, (select count(*) from models where brand_id = b.brand_id) as modelc from brands as b limit '.$perpage.' offset '.$page.'';
    $query = $this->db->query($query);
    $query = $query->result();
    return $query;

请帮助我将以上代码转换为Codeigniter Active Record。

1 个答案:

答案 0 :(得分:5)

这是活动记录中的查询

 $rows =   $this->db->select('b.brand_id,b.name')
    ->select('(select count(*) from items where brand_id = b.brand_id) as itemc',FALSE)
    ->select('(select count(*) from models where brand_id = b.brand_id) as modelc',FALSE)
    ->from('brands as b')
    ->limit($perpage,$page)->get()->result();