Search code examples
phpmysqlcodeigniteractiverecordcorrelated-subquery

How to use correlated subquery into Active record query in Codeigniter


I am working on to get the customer details from different tables. I have created and tested this query and it's working fine. The Problem is how to the user (convert) this query into Active Records query. Thanks You.

            SELECT c.cust_id, `c`.`cust_contact_name`, `c`.`cust_active_flag`, 
            (select COUNT(`pm`.`cust_id`)  from property_master as pm 
            Where pm.cust_id = c.cust_id) as prop_count,
            (select a.addr_phoneno1 from address as a
            WHERE a.cust_id = c.cust_id AND a.addr_type_flag IN ('C', 'CP')) as cust_phone,
            (select count(ci.cust_id) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as inquiry_count,
            (select max(inq_date) from customer_inquiry as ci
            WHERE ci.cust_id = c.cust_id) as last_inq_date
            FROM customer as c
            GROUP BY c.cust_ID

Solution

  • CodeIgniter Active record classes don't have direct support for sub-queries. You can use any 3rd party library like NTICompass CodeIgniter-Subqueries or $this->db->query(); to execute your query.

    Still, you can use the following way. But I will suggest to use $this->db->query();

    $this->db->select('c.cust_id, `c`.`cust_contact_name`, `c`.`cust_active_flag`, 
                (select COUNT(`pm`.`cust_id`)  from property_master as pm ' Where pm.cust_id = c.cust_id) as prop_count, (select a.addr_phoneno1 from address as a
                WHERE a.cust_id = c.cust_id AND a.addr_type_flag IN ('C', 'CP')) as cust_phone,
                (select count(ci.cust_id) from customer_inquiry as ci
                WHERE ci.cust_id = c.cust_id) as inquiry_count,
                (select max(inq_date) from customer_inquiry as ci
                WHERE ci.cust_id = c.cust_id) as last_inq_date)
             ->from('customer c');
    $this->db->group_by('c.cust_ID');
    $result = $this->db->get();