Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping WHERE clauses in Codeigniter

I want to produce the following SQL code using Active Records in Codeigniter:

WHERE name != 'Joe' AND (age < 69 OR id > 50)

Doing the following seems to be as far as I can get, I cant figure out how to group them

$this->db->select()->from('users')->where('name !=', 'Joe')->where('age <', 69)->or_where('id <', $id); 

Any ideas? My SQL query is too complex so I dont wish to rewrite everything in traditional SQL.

UPDATE

My SQL code is dynamically generated depending on the values of certain parameters passed into the model method. The problem with not being able to use parenthesis causes a problem because the operator precedence is such that AND is evaluated first before OR.

*Here is a chunk of my active records code, where there are some other code before and after it:

            ... some $this->db->where() ...
            ... some $this->db->where() ...

    if($price_range) {
        $price_array = explode('.', $price_range);
        for($i = 0; $i < count($price_array); $i++) {
            if($i == 0) {
                $this->db->where('places.price_range', $price_array[$i]);
            } else {
                $this->db->or_where('places.price_range', $price_array[$i]);
            }
        }

    }

            ... some $this->db->where() ...
            ... some $this->db->where() ...

The problem comes because I am using $this->db->or_where() which introduces a OR clause that throws the operator precedence into disarray without being able to use ( ) to change the order.

** Is there any way to solve this? **

like image 540
Nyxynyx Avatar asked Jun 24 '11 15:06

Nyxynyx


2 Answers

In Codeigniter 3.0.3 you can do it simple like this :

$this->db->select()
  ->from('users')
  ->where('name !=', 'Joe')
  ->group_start() // Open bracket
  ->where('age <', 69)
  ->or_where('id <', $id)
  ->group_end(); // Close bracket

Perhaps it can help

like image 172
Aldiyah Avatar answered Oct 17 '22 14:10

Aldiyah


You can use one large string.

$this->db->select()->from('users')->where("name != 'Joe' AND (age < 69 OR id > 50) ");

like image 22
Jrod Avatar answered Oct 17 '22 14:10

Jrod