views:

304

answers:

3

I have this

SELECT *
FROM categoryTable
WHERE categoryId NOT
IN (

SELECT categoryId
FROM userMenuTable
WHERE cookieId = 'bang4b544417a41b6'
)

but I would like it use codeigniters active record class so using

$this->db

syntax, I was hoping someone would help me convert this?

A: 

It's not possible. CodeIgniter ActiveRecord implementation doesn't support nested queries.

Alix Axel
sadtrombone.com
Matt
+6  A: 

Two ways to do this:

Plain SQL:

$this->db->query('SELECT * FROM categoryTable WHERE categoryId NOT IN (
    SELECT categoryId FROM userMenuTable WHERE cookieId = "bang4b544417a41b6"
)');

Active Record + Plain WHERE SQL

$this->db->where('categoryId', 'NOT IN (
    SELECT categoryId FROM userMenuTable WHERE cookieId = "bang4b544417a41b6"
)', FALSE);

$this->db->get('categoryTable');

You can put Plain SQL into a WHERE clause by adding FALSE in as the third argument in db->where();

It is a shame there is nothing neater for doing this, but Active Record is only intended for simple queries with joins, orders, limits, etc.

Phil Sturgeon
Thanks Phil, I have just gone with RAW sql for now, much appreciated response, beats "It's not possible".
sico87
A: 
$this->db->select('categoryId');
$this->db->where('cookieId','bang4b544417a41b6');
$this->db->from('userMenuTable');
$in_query = $this->db->_compile_select();
$this->db->_reset_select(); // dont forget this!

$this->db->select('field1, field2, field3'); // its a best practice not to use *
$this->db->from('categoryTable');

// look at the 3rd param, if you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks
$this->db->where("categoryId NOT IN ($in_query)", NULL, FALSE);

$query = $this->db->get();
$result = $query->result();
$query->free_result(); // optional, used when there are many queries
Martin Schaer