这是我的问题:MySQL "Or" Condition
解决方案是将 OR 语句分组,但我正在使用 CodeIgniters Active Record。有没有办法使用 Active Record 对 OR 语句进行分组?还是我必须自己编写查询?
我正在使用 $this->db->where()
和 $this->db->or_where()
它像这样编写查询:
其中标题 = 'foobar' AND 类别 = 2 或类别 = 3
但我需要的是:
WHERE title = 'foobar' AND(类别 = 2 或类别 = 3)
我做不到:
$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");
因为我使用 foreach 循环添加 OR
最佳答案
您可以按照说明手动执行此操作 here :
Custom string: You can write your own clauses manually:
$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 ]);
更新
查看this question上的答案如果您使用的是 CI 2.2。 选择已接受的答案之外的答案。
或者直接尝试this :
$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);
关于php - CodeIgniter Active Record - 组 OR 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26624535/