phpmysqlcodeigniteractiverecordquery-builder

Convert raw MYSQL query with DISTINCT and INNER JOINs to CodeIgniter active record syntax


I have the query below that works fine when I use it in phpMyAdmin, I am just a bit unsure how to do it within the CI framework when I have the m.id etc in place.

Query:

SELECT DISTINCT m.name, m.id, c.id, c.name
FROM  `default_ps_products` p
INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id

Solution

  • There are many ways.

    Example 1:

    $result = $this->db
        ->select('m.name, m.id, c.id, c.name')
        ->distinct()
        ->join('default_ps_products_manufacturers m', 'p.manufacturer_id=m.id')
        ->join('default_ps_product_x_cats x', 'p.id=x.product_id')
        ->join('default_ps_products_categories c', 'x.category_id=c.id')
        ->get('default_ps_products p')
        ->result();
    
    echo $this->db->last_query();
    

    Sometimes the active record can't produce the query you want. So you can write it yourself.

    Example 2:

    $query = "SELECT DISTINCT m.name, m.id, c.id, c.name
               FROM  `default_ps_products` p
               INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
               INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
               INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id";
    
    $result = $this->db
        ->query($query)
        ->result();
    
    echo $this->db->last_query();
    

    In this second example, db::query() can take an array as the second parameter that will replace any question marks (?) within $query with the respective value. For example say you needed to add some where values to your query.

    Example 3:

    $query = "SELECT DISTINCT m.name, m.id, c.id, c.name
              FROM  `default_ps_products` p
              INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
              INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
              INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id
              WHERE c.id=?";
    
    $result = $this->db
        ->query($query, array(1))
        ->result();
    
    echo $this->db->last_query();