动态Active Record查询中的Codeigniter括号

时间:2011-07-01 20:17:20

标签: mysql arrays codeigniter activerecord

我正在使用ActiveRecord

生成如下查询
SELECT * FROM (`foods`) WHERE `type` = 'fruits' AND 
       `tags` LIKE '%green%' OR `tags` LIKE '%blue%' OR `tags` LIKE '%red%'

tags和值的数量未知。数组是动态创建的。下面我添加了一个可能的数组。

$tags = array (                 
        '0'     => 'green'.
        '1'     => 'blue',
        '2'     => 'red'
);  

有一个标签数组,我使用以下循环来创建我在顶部发布的查询。

$this->db->where('type', $type); //var type is retrieved from input value

foreach($tags as $tag):         
     $this->db->or_like('tags', $tag);
endforeach; 

问题:我需要在LIKE子句中添加括号,如下所示:

SELECT * FROM (`foods`) WHERE `type` = 'fruits' AND 
      (`tags` LIKE '%green%' OR `tags` LIKE '%blue%' OR `tags` LIKE '%red%')

如果括号内的内容是静态的,但foreach循环将我抛弃,我知道如何实现这一目标。

8 个答案:

答案 0 :(得分:35)

来自CI维基:

  

codeignighter ActiveRecord功能   允许您创建SQL查询   相对简单而且   数据库独立,但有   isno具体支持包括   SQL查询中的括号。

例如,当你想要一个where语句出现在下面的时候:

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

这可以通过将字符串输入CI-> db-> where()函数来解决,在这种情况下,您将需要专门转义值。

请参阅以下示例:

$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子句:

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

答案 1 :(得分:17)

在CI 3.0-dev中,您可以在查询中添加组:

$this->db->select('id, title')
->group_start()
->or_like([ 'title' => $s, 'id' => $s ])
->group_end()                
->where([ 'b_del' => 0 ]);

产地:

SELECT `id`, `title`, `venda1`
FROM `itens`
WHERE   
(
`title` LIKE '%a%' ESCAPE '!'
OR  `id` LIKE '%a%' ESCAPE '!'
 )
AND `b_del` =0 

答案 2 :(得分:0)

关于The Silencer的解决方案,我写了一个小函数来帮助建立类似的条件

function make_like_conditions (array $fields, $query) {
    $likes = array();
    foreach ($fields as $field) {
        $likes[] = "$field LIKE '%$query%'";
    }
    return '('.implode(' || ', $likes).')';
}

你会这样使用它:

$search_fields = array(
    'field_1',
    'field_2',
    'field_3',
);
$query = "banana"
$like_conditions = make_like_conditions($search_fields, $query);
$this->db->from('sometable')
    ->where('field_0', 'foo')
    ->where($like_conditions)
    ->get()

答案 3 :(得分:0)

只需添加我的成功解决方案:

$this->db->where("(table.field = $variable OR table.field IS NULL)");

答案 4 :(得分:0)

使用codeigniter 3

$this->db->select('*');
    $this->db->from($this->MasterMember);
    $this->db->group_start();
    $this->db->where($this->IDCardStatus, '1');
    $this->db->or_where($this->IDCardStatus, '2');
    $this->db->group_end();

    if ($searchKey1 != null) {
        $this->db->group_start();
        $this->db->like($this->MemberID, $searchKey1);
        $this->db->or_like($this->FirstName, $searchKey2);
        $this->db->or_like($this->LastName, $searchKey3);
        $this->db->group_end();
    }

    $this->db->limit($limit, $offset);


    $data = $this->db->get();

这是我的本机查询

SELECT
    * 
FROM
    `Member` 
WHERE ( `Member`.`IDCardStatus` = '1' OR `Member`.`IDCardStatus` = '2' ) 
AND ( `Member`.`MemberID` LIKE '%some_key%' ESCAPE '!' OR `Member`.`FirstName` LIKE '%some_key%' ESCAPE '!' OR `Member`.`LastName` LIKE '%some_key%' ESCAPE '!' ) 
    LIMIT 10

答案 5 :(得分:0)

更新代码点火器4:

$builder->select('*')->from('my_table')
        ->groupStart()
            ->where('a', 'a')
            ->orGroupStart()
                    ->where('b', 'b')
                    ->where('c', 'c')
            ->groupEnd()
    ->groupEnd()
    ->where('d', 'd')
->get();

// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

摘自https://codeigniter.com/user_guide/database/query_builder.html#query-grouping

上的官方文档

答案 6 :(得分:-1)

你不能在ActiveRecord中添加括号,但是你可能正在寻找WHERE IN?

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

答案 7 :(得分:-1)

$likes = array (                 
    '0'     => 'green'.
    '1'     => 'blue',
    '2'     => 'red'
);  
$where_like = "("; 
$or_counter = 1;
foreach($likes as $like_key => $like_val):
    $or_content = ($or_counter > 1) ?'OR': '';
    $newlikeval = $this->db->escape_like_str($like_val);
    $where_like .= $or_content." `$like_key` LIKE  '%$newlikeval%' ";
    $or_counter++;
endforeach;
$where_like .= ")";
$this->db->where($where_like);