如何在Codeigniter 3中一起使用like,or_like和get_where

时间:2016-07-25 20:13:21

标签: codeigniter

我正在尝试使用关键字进行搜索,但仅在business_type为制造商的行中进行搜索,但它不起作用并且正在获取所有行。这是我模型中的方法:

public function search($keyword) {
    $this->db->like('category',$keyword);
    $this->db->or_like('keyword',$keyword);
    $this->db->or_like('products_deals_with',$keyword);
    $this->db->or_like('buisness_name',$keyword);
    $params['conditions'] = array(
        'business_type' => 'manufacturer'
    );
    $query = $this->db->get_where('business_listings', $params['conditions']);
    return $query->result_array();
}

生成的查询是:

SELECT * FROM `business_listings`
WHERE `category` LIKE '%%' ESCAPE '!'
OR `keyword` LIKE '%%' ESCAPE '!'
OR `products_deals_with`LIKE '%%' ESCAPE '!'
OR `buisness_name` LIKE '%%' ESCAPE '!'
AND `business_type` = 'manufacturer'

2 个答案:

答案 0 :(得分:5)

我找到了解决方案。我要使用$ this-> db-> group_start();和$ this-> db-> group_end();

public function search($keyword) {

    $this->db->select('*');
    $this->db->where("business_type = 'manufacturer'");
    $this->db->group_start();
    $this->db->like('category',$keyword);
    $this->db->or_like('keyword',$keyword);
    $this->db->or_like('products_deals_with',$keyword);
    $this->db->or_like('buisness_name',$keyword);
    $this->db->group_end();
    $query = $this->db->get('business_listings');
    // echo $this->db->last_query();
    return $query->result_array();

}

生成的查询:

SELECT * FROM `business_listings`
WHERE `business_type` = 'manufacturer'
AND (
`category` LIKE '%%' ESCAPE '!'
OR `keyword` LIKE '%%' ESCAPE '!'
OR `products_deals_with` LIKE '%%' ESCAPE '!'
OR `buisness_name` LIKE '%%' ESCAPE '!' )

答案 1 :(得分:0)

只需添加$this->db->group_start();$this->db->group_end();

$this->db->group_start();
$this->db->like('category',$keyword);
$this->db->or_like('keyword',$keyword);
$this->db->or_like('products_deals_with',$keyword);
$this->db->or_like('buisness_name',$keyword);
$this->db->group_end();

$params['conditions'] = array(
    'business_type' => 'manufacturer'
);

$query = $this->db->get_where('business_listings', $params['conditions']);
return $query->result_array();