从原始sql更改为codeigniter活动类

时间:2010-01-18 15:06:06

标签: php mysql activerecord codeigniter

我有这个

SELECT *
FROM categoryTable
WHERE categoryId NOT
IN (

SELECT categoryId
FROM userMenuTable
WHERE cookieId = 'bang4b544417a41b6'
)

但我希望它使用codeigniters活动记录类,所以使用

$this->db

语法,我希望有人能帮助我转换这个?

3 个答案:

答案 0 :(得分:6)

两种方法:

纯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');

通过在db-> where()中添加FALSE作为第三个参数,可以将Plain SQL放入WHERE子句中。

遗憾的是,没有什么可以做到这一点,但Active Record仅适用于带有连接,订单,限制等的简单查询。

答案 1 :(得分:1)

$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

答案 2 :(得分:0)

这是不可能的。 CodeIgniter ActiveRecord实现不支持嵌套查询。