【问题标题】:Changing from raw sql to codeigniters active class从原始 sql 更改为 codeigniters 活动类
【发布时间】:2011-01-06 09:52:32
【问题描述】:

我有这个

SELECT *
FROM categoryTable
WHERE categoryId NOT
IN (

SELECT categoryId
FROM userMenuTable
WHERE cookieId = 'bang4b544417a41b6'
)

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

$this->db

语法,我希望有人能帮我转换一下吗?

【问题讨论】:

    标签: php mysql activerecord codeigniter


    【解决方案1】:

    两种方法:

    普通 SQL:

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

    Active Record + 普通 WHERE SQL

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

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

    很遗憾,没有什么比这更简洁的了,但 Active Record 仅适用于带有连接、订单、限制等的简单查询。

    【讨论】:

    • 谢谢菲尔,我现在刚刚使用 RAW sql,非常感谢您的回复,击败了“不可能”。
    【解决方案2】:
    $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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多