使用CI activerecords组合`where`和`like`语句

时间:2012-05-08 03:12:15

标签: php sql codeigniter

长话短说:是否可能,如果是 - 如何构建一个看起来有点像这样的查询

SELECT * FROM a
    WHERE row = 1 AND 
    (other_row LIKE '%..%' OR another_row LIKE '%..%')

基本上我无法找到解决这个问题的方法。我似乎无法想象如何将括号添加到activerecords查询。这甚至可能吗?

我目前的代码:

$data = $this->where('row', 1)
    ->like('another_row', '...')        
    ->or_where('row', 1)
    ->like('other_row', $search)                
    ->get('a')
    ->result();

结果:

SELECT * FROM (`a`) WHERE `row` = 1 OR `row` = 1 AND `another_row` LIKE '%...%' AND other_row` LIKE '%...%'

6 个答案:

答案 0 :(得分:6)

你可以试试这个。

   $query = $this->db->select('*')
            ->from('a')
            ->where('row',1)
            ->where("(other_row LIKE '%%' OR another_row LIKE '%%' )")
            ->get();


    foreach ($query->result() as $row) {
        //do sth.
    }

您可以编写自定义查询字符串(来自活动记录类)

 Custom string:
 You can write your own clauses manually:

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

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

答案 1 :(得分:1)

为什么不尝试这个:

    $this->db->where("row = 1 AND 
        (other_row LIKE '%..%' OR another_row LIKE '%..%')");
$this->db->get('a');

您可以在CI中编写自定义WHERE。如果不是您想要的,请随时解释

答案 2 :(得分:0)

我也遇到了or_where的问题,所以我只是将自定义查询设为

$this->db->query("SELECT * FROM `a` WHERE `row`=1 AND (CONDITION1 OR CONDITION2)")

答案 3 :(得分:0)

$sql= "SELECT * FROM `a`
WHERE row = '1' AND 
(other_row LIKE '%" . $value . "%' OR another_row LIKE '%" . $value . "%')";
 $this->db->query($sql);

答案 4 :(得分:0)

您可以使用以下内容:

$this->db->like('title', 'match', 'before');

它会产生:

WHERE `title` LIKE '%match' ESCAPE '!'

答案 5 :(得分:0)

$this->db->where('salary_range_min >= ',$salarymin)
$this->db->where('salary_range_max <= ',$salarymax)
$this->db->where('job_title like '.$title.'% or skill like %'.$title.'%');
// OR */
$this->db->where('job_title like '.$title.'% or skill like %'.$title.'%',FALSE);
// OR */
$this->db->where('job_title like '.$title.'% or skill like %'.$title.'%',NULL);

尝试一下