[英]Changing from raw sql to codeigniters active class
我有这个
SELECT *
FROM categoryTable
WHERE categoryId NOT
IN (
SELECT categoryId
FROM userMenuTable
WHERE cookieId = 'bang4b544417a41b6'
)
但我希望它使用codeigniters活动记录类,所以使用
$this->db
语法,我希望有人能帮我转换一下?
有两种方法可以做到这一点:
普通SQL:
$this->db->query('SELECT * FROM categoryTable WHERE categoryId NOT IN (
SELECT categoryId FROM userMenuTable WHERE cookieId = "bang4b544417a41b6"
)');
活动记录+普通WHERE SQL
$this->db->where('categoryId', 'NOT IN (
SELECT categoryId FROM userMenuTable WHERE cookieId = "bang4b544417a41b6"
)', FALSE);
$this->db->get('categoryTable');
通过将FALSE in作为db-> where();中的第三个参数,可以将Plain SQL放入WHERE子句中。
遗憾的是,这样做没有什么整洁的方法,但是Active Record仅适用于具有联接,顺序,限制等的简单查询。
$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
这是不可能的。 CodeIgniter ActiveRecord实现不支持嵌套查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.