3

Is there any way to get nested where clauses? e.g.:

SELECT * FROM table WHERE (colA = 'valueA' AND colB = 'valueB') OR (colA = 'valueC' AND colB = 'valueD')

I know I could just write this into a query function call e.g.:

$this->db->query("SELECT ...")

But I was wondering if there was a "proper" way to do it in codeigniter e.g.:

$this->db->where(array('colA'=>'valueA'), array('colB'=>valueB'))->or_where(array('colA'=>'valueC'), array('colB'=>'valueD'))

thanks

2 Answers 2

7

With codeigniter 3, now there is, see the update!
There's no where() method usage variant with arrays that would allow you to do that. In these situations i usually just build the part in one long string like this:

$this->db->where("
    (
    (colA = '".$this->db->escape($v0)."' and colB = '".$this->db->escape($v1)."') 
    or 
    (colA = '".$this->db->escape($v2)."' and colB = '".$this->db->escape($v3)."') 
    )
");

Escaping can be done with escape(does some autodetection) or escape_str or escape_like_str manually depending on what the parameter expected to be or what the predicate in use.

If i'm on a project that uses the Datamapper library, i prefer to use the group_start() and group_end() methods when building these kind of queries, they have a lot of different flavor of these.

Update

Now with, Codeigniter 3 which have grouping methods in the query builder, so you can do ->group_start()s and ->group_end()s.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, thanks for that! :) That's a bit better than doing the $this->db->query("...") version. Thank you.
-1

You can also try like

$this->db->where(condition1);
$this->db->or_where(condition2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.