【发布时间】: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
是否可以将 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
我知道这有点晚了,但我在查看这篇文章时发现了这个帖子,并找到了比 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();
【讨论】:
是的。 $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 子句的四种方法。
【讨论】:
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();
【讨论】: