多个连接与whereI,like和or_like CodeIgniter 3 Active Records

时间:2016-09-22 11:39:43

标签: php mysql codeigniter activerecord codeigniter-3

我正在尝试这个:

$guests = 2;

我提供3位客人和阿尔巴尼亚国家(每桌1排)。但是,如果like我得到了这一行。如果我使用or_likewhere而不是or_where$this->db->or_where('l.city LIKE', $location.'%');,则相同。如果我评论这一行:

$guests != 3

一切正常,如果$guests = 3我没有结果,$this-db->last_query()会产生1行。

使用SELECT 'l'.'id', 'd'.'guests', 'l'.'city', 'l'.'country' FROM 'offers' as 'o' LEFT JOIN 'location' as 'l' ON 'l'.'id' = 'o'.'id' LEFT JOIN 'desc' as 'd' ON 'd'.'id' = 'o'.'id' WHERE 'd'.'guests' = 3 AND 'o'.'completed' = 1 AND 'l'.'country' LIKE 'a%' OR 'l'.'city' LIKE 'a%' LIMIT 5生成的查询是:

$guests

如何进行此查询? 选择已完成= 1的值,来宾= $location以及{{1}}等城市或国家/地区。

3 个答案:

答案 0 :(得分:1)

试试这段代码

$location = 'a';
$this->db->select('l.id, d.guests, l.city, l.country');
$this->db->from('offers as o');
$this->db->join('location as l', 'l.id = o.id', 'left');
$this->db->join('desc as d', 'd.offer_id = o.id', 'left');
$this->db->where('d.guests', $guests);
$this->db->where('o.completed', 1);
$this->db->where("(l.country LIKE '".$location."%' or l.city LIKE '".$location."%')");
$this->db->limit(5);

答案 1 :(得分:0)

您需要使用Query grouping

$location = 'a';
$this->db->select('l.id, d.guests, l.city, l.country');
$this->db->from('offers as o');
$this->db->join('location as l', 'l.id = o.id', 'left');
$this->db->join('desc as d', 'd.offer_id = o.id', 'left');
$this->db->where('d.guests', $guests);
$this->db->where('o.completed', 1);
$this->db->->group_start();
$this->db->where('l.country LIKE', $location.'%');
$this->db->or_where('l.city LIKE', $location.'%');
$this->db->group_end();
$this->db->limit(5);

另外,请查看like and or_like方法以避免使用此'l.country LIKE'之类的代码。

答案 2 :(得分:0)

试试这个

$location = 'a';
 $this->db->select('l.id, d.guests, l.city, l.country');
 $this->db->from('offers as o');
 $this->db->join('location as l', 'l.id = o.id', 'left');
 $this->db->join('desc as d', 'd.offer_id = o.id', 'left');
 $this->db->where('d.guests', $guests);
 $this->db->where('o.completed', 1);
 $this->db->like('l.country',$location,'after');
 $this->db->or_like('l.city',$location,'after');
 $this->db->limit(5);