php - CodeIgniter Active Record - 组 OR 语句

标签 php mysql codeigniter

这是我的问题: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/

相关文章:

php - 如何减少标题中的主页链接大小?

php - 如何在 PHP 中编写正则表达式来删除特殊字符?

mysql - UPDATE 语句的 where 子句中的子查询

mysql - select 中的 SQL 循环

mysql - 同一张表中的删除语句

php - 根据 CodeIgniter 上的子字符串查询按 id 进行分组

php - 无法在实时服务器中发布富文本编辑器内容?

php - 从wordpress上传文件到amazon s3

php - 使用 CodeIgniter Active Records 插入数据

php - 如何从表中获取记录并将其显示在另一个 View 中