phpsqlcodeigniterquery-builderlogical-grouping

Combining `where` and `like` statements by using the CI activerecords


To cut a long story short: Is it possible and if it is - how can I build a query that looks somewhat like this one

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

Basically I can't come up / find a solution to this problem. I just can't seem to figure how to add the brackets to the active records query. Is that even possible?

My current code:

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

Undesirable Result:

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

Solution

  • You can try this.

       $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.
        }
    

    You can write custom query string (from active record class)

     Custom string:
     You can write your own clauses manually:
    
     $where = "name='Joe' AND status='boss' OR status='active'";
    
     $this->db->where($where);