【问题标题】:How to group WHERE clauses with active record?如何将 WHERE 子句与活动记录分组?
【发布时间】:2012-01-18 18:46:50
【问题描述】:

下面的活动记录代码没有像我需要的那样对 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);

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

    不幸的是,似乎没有一种干净的方法可以做到这一点。 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%')");
    

    【讨论】:

      【解决方案2】:

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

      或许有帮助

      【讨论】:

      • 其实这是最好的解决方案,干净,简单,可以很好地用于其他目的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多