且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态 Active Record 查询中的 Codeigniter 括号

更新时间:2023-09-24 10:46:22

来自 CI wiki:

From the CI wiki:

codeignighter ActiveRecord 功能允许您创建 SQL 查询相对简单和独立于数据库,但是有没有特别支持包括SQL 查询中的括号.

The codeignighter ActiveRecord feature allows you to create SQL queries relatively simply and database-independant, however there isno specific support for including parenthesis in an SQL query.

例如,当您希望 where 语句与以下内容类似时:

For example when you want a where statement to come out simmilarly to the folowing:

WHERE (field1 = value || field2 = value) AND (field3 = value2 || field4 = value2) 

这可以通过向 CI->db->where() 函数提供字符串来解决,在这种情况下,您需要专门转义您的值.

This can be worked around by feeding a string to the CI->db->where() function, in this case you will want to specifically escape your values.

看下面的例子:

$value=$this->db->escape($value);
$value2=$this->db->escape($value2);
$this->db->from('sometable');
$this->db->where("($field = $value || $field2 = $value)");
$this->db->where("($field3 = $value2 || $field4 = $value2)");
$this->db->get(); 

类似的解决方法可用于 LIKE 子句:

A simmilar workaround can be used for LIKE clauses:

$this->db->where("($field LIKE '%$value%' || $field2 LIKE '%$value%')");
$this->db->where("($field3 LIKE '%$value2%' || $field4 LIKE '%$value2%')");