Changing from raw sql to codeigniters active class
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?
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.
$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
It's not possible. CodeIgniter ActiveRecord implementation doesn't support nested queries.
精彩评论