Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to write Sub Queries in Codeigniter Active Record ?

Codeigniter didn’t provide an option to use subqueries with active record class. So today I would like to provide simple and possible comprehensive techniques on “creating Sub Queries with Codeigniter Active Record”.

Creating subquery in Codeigniter is as easy as creating the regular Active Record queries. The technique here is first we need to generate a query and the generated query we need to inject it into the main query as subQuery.

How to write Sub Queries in Codeigniter Active Record ?

So first we need to generate a subquery and store that generated the query in a variable as a string. After generating the subquery we will generate the main query by using a previously generated query as a subquery.

For Example – I am going to generate a blow query with active record methods

SELECT * FROM employees WHERE id IN(SELECT id FROM employees_backup); 
// Sub Query
$this->db->select('id')->from('employees_backup');
$subQuery =  $this->db->get_compiled_select();

// Main Query
$this->db->select('*')
         ->from('employees')
         ->where("id IN ($subQuery)", NULL, FALSE)
         ->get()
         ->result();

The NULL, FALSE in the where() method tells CodeIgniter not to escape the query.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments