Alex Rivera | Logout

Encapsulate a dynamic number of OR LIKE conditions with parentheses using CodeIgniter's active record methods

Asked 2011-07-01T20:17:20.217
26

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; 

The issue: I need to add parentheses around the LIKE clauses like below:

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

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

Edit
Report

1 Answer

-1

Going off of The Silencer's solution, I wrote a tiny function to help build like conditions

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

You'd use it like this:

$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()
answered 2013-06-04T18:58:51.913

Your Answer