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 subquery we will generate the main query by using previously generated query as a subquery.

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

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.

5 1 vote
Article Rating
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jeralyn Maturan
Jeralyn Maturan
5 years ago

Good afternoon. I would like to insert data in MySQL using the values returned from my select statement (attached is the print screen of my query in database). The query did well in the database. My question is, how will I enter this in DB using codeigniter? Thanks for helping!

arjun
5 years ago

use $this->db->query() method to run raw query

Jeralyn Maturan
Jeralyn Maturan
5 years ago
Reply to  arjun

in what part of the CI should I insert that code?

ramzi
ramzi
2 months ago

select a.kode_brg,c.nama_brg,a.harga_beli from mcmharga_beli a
      inner join(select kode_brg,max(tgl_berlaku) tgl_berlaku from mcmharga_beli
      where tgl_berlaku<=”$tgl_brlaku” group by kode_brg) 
      b on b.kode_brg=a.kode_brg and b.tgl_berlaku=a.tgl_berlaku
      inner join mcmbarang c on c.kode_brg=a.kode_brg
      where a.kode_brg=”$kode_brg

how i can make the code above in sub query Codigniter ?

DMCA.com Protection Status
4
0
Would love your thoughts, please comment.x
()
x