【问题标题】:Codeigniter Active Record 'where_or' groupingCodeigniter Active Record 'where_or' 分组
【发布时间】:2012-02-03 14:38:42
【问题描述】:

是否可以将 and_where / or_where / or_like... 语句分组在一起,以免与其他 and/where 语句混合。

会导致的事情

WHERE city = 'My City' AND state = 'My State' AND (name LIKE %name1% 或名称 LIKE %name2%)

【问题讨论】:

    标签: mysql codeigniter activerecord


    【解决方案1】:

    我知道这有点晚了,但我在查看这篇文章时发现了这个帖子,并找到了比 Sean 提出的更好的解决方案。

    $name = 'Bob';
    
    $this->db->where('city', 'My City');
    $this->db->where('state', 'My State');
    $this->db->group_start();
        $this->db->like('name', $name);
        $this->db->or_like('name', $name);
    $this->db->group_end();
    

    【讨论】:

    • 此解决方案适用于 Codeigniter 3+,但不适用于 Codeigniter 2
    【解决方案2】:

    是的。 $this->db->where() 允许您手动编写子句。你可以这样做:

    $this->db->where('city', 'My City');
    $this->db->where('state', 'My State');
    $this->db->where('(name LIKE %name1% OR name LIKE %name2%)', null, false);
    

    将第三个参数设置为 false 可防止 CodeIgniter 尝试向子句添加反引号。

    查看Active Record documentation。标题为 $this->db->where(); 的部分解释了可用于设置 WHERE 子句的四种方法。

    【讨论】:

      【解决方案3】:

      group_start()group_end() 这两个函数已在 CodeIgniter 3.0.3 中实现。根据原始问题,这是更好的实现。

      $name1 = 'Bob';
      $name2 = 'John';
      
      $this->db->where('city', 'My City');
      $this->db->where('state', 'My State');
      $this->db->group_start();
      $this->db->like('name', $name1);
      $this->db->or_like(('name', $name2);
      $this->db->group_end();
      

      【讨论】:

        猜你喜欢
        • 2014-12-24
        • 2012-03-24
        • 1970-01-01
        • 2012-06-05
        • 2013-02-18
        • 2013-06-14
        • 2011-07-10
        • 2012-07-24
        • 1970-01-01
        相关资源
        最近更新 更多