Codeigniter parentheses in dynamic Active Record query

后端 未结 8 1587
死守一世寂寞
死守一世寂寞 2020-12-05 23:38

I\'m producing a query like the following using ActiveRecord

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


        
8条回答
  •  臣服心动
    2020-12-06 00:14

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

提交回复
热议问题