如何将WHERE子句与活动记录分组?

时间:2012-01-18 18:46:50

标签: php codeigniter activerecord

下面的活动记录代码没有像我需要的那样对WHERE子句进行分组......

        $this->db->where('customers_id',$this->user->getCurrentUserProperty('id'))
        $this->db->like('delivery_name', $this->input->post('search'));
        $this->db->or_like('customers_company', $this->input->post('search'));
        $this->db->or_like('customers_company2', $this->input->post('search'));
        $this->db->or_like('customers_company3', $this->input->post('search'));
        $this->db->or_like('customers_company4', $this->input->post('search'));

这会生成

WHERE `customers_id` = 31509 AND `delivery_name` LIKE '%str%' OR `customers_company` LIKE '%str%'"

我需要输出在它周围括号括起来......我怎么能这样做?

WHERE `customers_id` = 31509 AND (`delivery_name` LIKE '%str%' OR `customers_company` LIKE '%str%')"

注意:我讨厌像这样烦人的时间的活跃记录

如果我使用下面的方法,我该如何清理输入以使其不是查询的原始内容?

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

2 个答案:

答案 0 :(得分:4)

不幸的是,似乎没有一种干净的方法可以做到这一点。 where接受一个字符串作为子句,所以你可以这样做(是的,我知道,它不漂亮):

$search = $this->db->escape_like_str($this->input->post('search'));
$this->db->where('customers_id',$this->user->getCurrentUserProperty('id'));
$this->db->where("(`delivery_name` LIKE '%$search%' OR `customers_company` LIKE '%$search%')");

答案 1 :(得分:1)

在Codeigniter 3.0.3中,您可以这样简单地完成:

$this->db->where('customers_id',$this->user->getCurrentUserProperty('id'));
$this->db->group_start();
$this->db->like('delivery_name', $this->input->post('search'));
$this->db->or_like('customers_company', $this->input->post('search'));
$this->db->or_like('customers_company2', $this->input->post('search'));
$this->db->or_like('customers_company3', $this->input->post('search'));
$this->db->or_like('customers_company4', $this->input->post('search'));
$this->db->group_end();

也许它可以提供帮助

相关问题