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

问题描述 投票:0回答:2

我正在尝试使用关键字进行搜索,但仅限于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'
php codeigniter activerecord sql-like logical-grouping
2个回答
15
投票

我找到了解决方案。我必须使用 $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
投票

只需添加

$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();
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.