在动态的活动记录查询codeigniter括号括号、动态、codeigniter

2023-09-08 18:49:19 作者:深知我者才久居我心

我产生像一个查询中使用的ActiveRecord以下

I'm producing a query like the following using ActiveRecord

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

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

The number of tags and values is unknown. Arrays are created dynamically. Below I added a possible array.

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

为标签的数组,我用下面的循环来创造我贴在上面的查询。

Having an array of tags, I use the following loop to create the query I posted on top.

$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循环抛出我送行。

I know how to accomplish this if the content within the parentheses was static but the foreach loop throws me off..

推荐答案

从CI维基:

cignighter ActiveRecord的功能的$ C $   允许您创建SQL查询   相对简单和   数据库独立,但有   对于ISNO包括具体的支持   括号中的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语句来simmilarly出来了如下因素:

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->其中()函数,在这种情况下,你会想逃离专门的值来避开这一情况。

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(); 

一个simmilar解决方法可以用于类似的条款:

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%')");