这是我的问题:MySQL“ Or”条件
解决方案是对OR语句进行分组,但是我正在使用CodeIgniters Active Record。有没有一种方法可以使用Active Record对OR语句进行分组?还是我必须自己编写查询?
我使用的是$this->db->where()
与$this->db->or_where()
它这样写查询:
WHERE title = 'foobar' AND category = 2 OR category = 3
但我需要的是:
WHERE title = 'foobar' AND (category = 2 OR category = 3)
我不能这样做:
$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");
因为我正在使用foreach循环添加OR
您可以按照此处所述手动进行操作:
自定义字符串:您可以手动编写自己的子句:
$ where =“ name ='Joe'AND status ='boss'OR status ='active'”;
$ this-> db-> where($ where);
至于你的问题:
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
在3.0-dev中:
$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()
->where([ 'category' => 1 ]);
如果您使用的是CI 2.2,请参阅此问题的答案。选择除已接受之外的答案。
或者干脆试试这个:
$categories = array(2, 3);
array_walk($categories, function(&$cat) { $cat = 'category = ' . $cat; });
$catstring = implode(" OR ", $categories);
$where = "category = 1 AND ($catstring)";
// => category = 1 AND (category = 2 OR category = 3)
$this->db->where($where);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句