问题
Hey.. I've run into a problem using several "like" in my sql-query (generated with Codeigniter's activerecord):
SELECT * FROM (`posts`) WHERE `city` LIKE '%test%' AND `title` LIKE '%%' OR `text` LIKE '%%'
Thing is, it appears to read this query as if there was a parenthesis around the first like and the second like, but I want there to be a parenthesis around the second and the last like (I want it to compare if the last or the next to last works).
How can I achieve this using Codeigniter's Active Record class?
Current code: if($type != 0) $this->db->where('type', $type);
$this->db->like('city', $area);
$this->db->like('title', $words);
$this->db->or_like('text', $words);
return $this->db->get('posts')->result_array();
回答1:
I don't think CI is adding any paranthesis. It will add an 'AND' between the first two statements and an 'OR' between the last two. To achieve what you want, I would write my own statement. It's very straightforward.
$sql = SELECT * FROM 'posts' WHERE city LIKE ? AND ( title LIKE ? OR text LIKE ? );
$query = $this->db->query($sql, array($area, $words, $words));
Notice how I've used binding. This automatically escapes characters for you.
回答2:
Previous answer is correct. I would like to add the following...
In Codeigniter supporting the following overall...
$this->db->like();
$this->db->or_like();
$this->db->not_like();
$this->db->or_not_like();
Hope this will help someone.
回答3:
this will do the trick
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
回答4:
when you have to use table join as well try following method
public function get_all_airports($para) {
$this->db->select('airports.name as air_name, airports.city, airports.type, airports.home_link, country.name as con_name');
$this->db->from('airports');
$this->db->join('country', 'airports.iso_country = country.code', 'inner');
$this->db->where("airports.type !=", "small_airport");
$this->db->where("airports.type !=", "closed");
$this->db->where("airports.type !=", "heliport");
$this->db->where("airports.type !=", "medium_airport");
$this->db->where("airports.type !=", "seaplane_base");
$where = "(country.name LIKE '%$para%' OR airports.city LIKE '%$para%')";
$this->db->where($where);
echo json_encode($this->db->limit(20)->get()->result());
}
来源:https://stackoverflow.com/questions/3489399/codeigniter-active-record-with-several-like-or