phpcodeigniterselectactiverecordquery-builder

Convert SQL with LEFT JOINs, WHERE and ORDER BY conditions executed with query() to CodeIgniter active record


I am trying to update my code from raw SQL query to CodeIgniter active records.

This here is my old code

public function get_categories($parent_id = 0) {

    $language_id = "1";

    $query = $this->db->query("
        SELECT *
        FROM " . $this->db->dbprefix . "category c
        LEFT JOIN " . $this->db->dbprefix . "category_description cd ON (c.category_id = cd.category_id)
        LEFT JOIN " . $this->db->dbprefix . "category_to_store c2s ON (c.category_id = c2s.category_id)
        WHERE c.parent_id = '" . (int)$parent_id . "'
            AND cd.language_id = '" . (int)$language_id . "'
            AND c2s.store_id = '" . (int)$language_id . "'
            AND c.status = '1'
        ORDER BY c.sort_order, LCASE(cd.name)
    ");

    return $query->result_array();
}

And I am trying to update it to new active record code below.

The problem I am having is it not getting the correct result by the id. And since upgrading to CI-3, my old code does not work.

public function get_categories($parent_id = 0) {
    $this->db->select('*');
    $this->db->from('category');
    $this->db->join('category_description', 'category_description.category_id = category.category_id', 'left');
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return false;
    }
 } 

How can I use the CodeIgniter join properly?


Solution

  • after upgrading to Codeigniter 3.0 you need to update your database config file:

    delete: $active_record = TRUE;

    add: $query_builder = TRUE;

    there is actually more to consider updating, the full documentation you find here:

    http://www.codeigniter.com/user_guide/changelog.html

    and

    http://www.codeigniter.com/user_guide/installation/upgrade_300.html