【问题标题】:CodeIgniter Active Record - Group OR statementsCodeIgniter Active Record - 组 OR 语句
【发布时间】:2014-12-24 19:32:16
【问题描述】:

这是我的问题:MySQL "Or" Condition

解决方案是将 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

【问题讨论】:

  • 实际上这不会获取任何行,因为它每次都会变成1 AND 0 0 AND 1 = FALSE 条件。
  • @karanthakkar 这只是一个获得想法的例子,但你是对的,哈哈
  • 你能发布foreach逻辑吗?如果它是一个数组,你可以使用 where_in 而不是使用 foreach。

标签: php mysql codeigniter


【解决方案1】:

您可以按照here 所述手动操作:

自定义字符串:您可以手动编写自己的子句:

$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,请参阅 this question 上的答案。 选择一个不被接受的答案

或者干脆试试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);

【讨论】:

  • 我正在使用 foreach 循环添加 OR,这样它就不起作用了。 3.0 开发部分看起来正是我需要的,但我使用的是 2.2 版
  • 您发布的链接的接受答案看起来是一个很好的解决方案,但为什么它有 8 个反对票?
  • 您发布的最后一个代码正是 OP 自己接受的答案,即“动态生成 SQL 查询并将其插入 $this->db->where()”。我不认为这很丑,这似乎是一个很好的答案。想知道为什么它有 8 个反对票?
  • @sol ,majidarif。正如我所提到的,CI 中有一个内置函数。
  • @sol 否决票似乎建议您放松字符串验证,但文档说: where() All values passed to this function are escaped automatically, producing safer queries.
【解决方案2】:

正如 OP 所说,您正在使用 foreach (array) 生成 OR 你可以简单地使用

    $cat_array=array(2,3,4,5,6,7);
    $this->db->select('col1, col2')->from('table')->where("col1",1)->where_in('col2', $cat_array);

会生成

SELECT `col1`, `col2` FROM (`table`) WHERE `col1` = 1 AND `col2` IN (2, 3, 4, 5, 6, 7) 

【讨论】:

  • OP 的问题似乎具有误导性,他试图构建的查询是错误的。如果是这样,那么这是最好的答案。
  • @majidarif 是的,但问题可能是相当误导性的 :)
  • 对于我的问题,我使用 where_in 所以 +1 使它工作,但它仍然没有回答我的问题如何使用 OR 来完成它
【解决方案3】:

您不能使用 DB 活动记录方法 (where, or_where) 操作地面条件查询,我建议在 where() 方法中作为 sting 传递

$this->db->where("category = 1 AND (category = 2 OR category = 3)");

【讨论】:

  • 我不能这样做,因为我正在使用 foreach 循环(更新了我的问题)
【解决方案4】:

在 Code Igniter 版本 3.0-dev 中,您可以使用 group_startgroup_end 在任何查询中添加组:

$this->db->select('col1, col2')
->where("category = 1")
->group_start()
->where("category = 2")
->or_where("category = 3")
->group_end();

生产:

SELECT `col1`, `col2`
FROM `table_name`
WHERE category = 1 AND (category = 2 OR category = 3);

【讨论】:

  • 我使用的是 2.2 版
猜你喜欢
  • 2013-09-26
  • 1970-01-01
  • 2013-04-11
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 2015-09-17
相关资源
最近更新 更多