Codeigniter parentheses in dynamic Active Record query

后端 未结 8 1589
死守一世寂寞
死守一世寂寞 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-05 23:55

    From the CI wiki:

    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.

    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) 
    

    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.

    See the following example:

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

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

提交回复
热议问题