phpmysqlcodeigniteractiverecordsql-order-by

Convert SELECT query with GROUP BY and ORDER BY COUNT(*) to CodeIgniter's active record


I want to write bellow mysql query in form of CodeIgniter active record

select c.*
from code c
left join code_like l on c.id = l.code_id
group by c.id
order by count(*) desc

I am try below query, but how to add order by count(*) desc

$this->db->select('*');
$this->db->from('code');
$this->db->join('code_like', 'code.id = code_like.id');
$this->db->group_by("code.id"); 
$query = $this->db->get();

Solution

  • This will work for you, as you have typos within your code

    $this->db->select('c.*,count(c.*) as data');
    $this->db->from('code c');
    $this->db->join('code_like cl', 'c.id = cl.code_id','left');
    $this->db->group_by('c.id');
    $this->db->order_by('data DESC');
    $result = $this->db->get->result_array();
    print_r($result);