Search code examples
phpcodeigniteractiverecordquery-builderlogical-grouping

Enclose portions of WHERE clause conditions in parentheses with CodeIgniter query builder methods


I have the following code:

$this->db->from('addresses');
$this->db->where('user_id', $this->session->userdata('user.id'));
$this->db->like('country',    $pSearch); 
$this->db->or_like('state',   $pSearch); 
$this->db->or_like('city',    $pSearch); 
$this->db->or_like('zip',    $pSearch); 

which generates the following SQL

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  `country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%'
ORDER BY `country` asc
LIMIT 15

Is there a way to make it generate it like this:

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  (`country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%')
ORDER BY `country` asc
LIMIT 15

As I want to get only the records for user_id = 1 and not for all users.


Solution

  • That seems to be a bug/limitation in CI ActiveRecord. You could try Ignited Query, which has the ability to handle nested WHERE clauses, and probably can handle the nested WHERE/LIKE the way you like.

    Check out this thread also for more info.