这是我的问题:MySQL“或”条件 https://stackoverflow.com/questions/8604380/mysql-or-condition
解决方案是将 OR 语句分组,但我正在使用 CodeIgniters Active Record。有没有办法使用 Active Record 对 OR 语句进行分组?或者我必须自己编写查询?
我在用着$this->db->where()
with $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
您可以按照说明手动执行此操作here https://ellislab.com/codeigniter/user-guide/database/active_record.html:
自定义字符串:您可以手动编写自己的子句:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
至于你的问题:
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
In 3.0-dev:
$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()
->where([ 'category' => 1 ]);
update
See the answers on this question https://stackoverflow.com/questions/6470267/grouping-where-clauses-in-codeigniter if you're using CI 2.2. Choose an answer other than the accepted.
或者只是尝试一下this https://eval.in/211243:
$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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)