sol
sol

Reputation: 440

CodeIgniter Active Record - Group OR statements

This is my problem: MySQL "Or" Condition

The solution is to group the OR statements, but i'm using CodeIgniters Active Record. Is there a way to group OR statements using Active Record? Or do I have to write the query myself?

I'm using $this->db->where() with $this->db->or_where()

It writes the query like this:

WHERE title = 'foobar' AND category = 2 OR category = 3

but what I need is:

WHERE title = 'foobar' AND (category = 2 OR category = 3)

I can't do this:

$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");

because i'm adding ORs using a foreach loop

Upvotes: 2

Views: 1733

Answers (4)

Karan Thakkar
Karan Thakkar

Reputation: 1467

as OP mentioned you are generating OR using foreach (array) you can simply use

    $cat_array=array(2,3,4,5,6,7);
    $this->db->select('col1, col2')->from('table')->where("col1",1)->where_in('col2', $cat_array);

will generate

SELECT `col1`, `col2` FROM (`table`) WHERE `col1` = 1 AND `col2` IN (2, 3, 4, 5, 6, 7) 

Upvotes: 0

majidarif
majidarif

Reputation: 19985

You can do it manually as stated here:

Custom string: You can write your own clauses manually:

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

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

As for your question:

$this->db->where("category = 1 AND (category = 2 OR category = 3)");

In 3.0-dev:

$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()                
->where([ 'category' => 1 ]);

update

See the answers on this question if you're using CI 2.2. Choose an answer other than the accepted.

Or simply try this:

$categories = array(2, 3);

array_walk($categories, function(&$cat) { $cat = 'category = ' . $cat; });

$catstring  = implode(" OR ", $categories);
$where      = "category = 1 AND ($catstring)";
// => category = 1 AND (category = 2 OR category = 3)

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

Upvotes: 1

Ashish Awasthi
Ashish Awasthi

Reputation: 1502

In the Code Igniter Version 3.0-dev you can add groups in any query using group_start and group_end :

$this->db->select('col1, col2')
->where("category = 1")
->group_start()
->where("category = 2")
->or_where("category = 3")
->group_end();

Produces:

SELECT `col1`, `col2`
FROM `table_name`
WHERE category = 1 AND (category = 2 OR category = 3);

Upvotes: 0

Girish
Girish

Reputation: 12127

you can't manipulate ground condition query using DB active record methods (where, or_where) , i would recommond to pass as sting in where() method

$this->db->where("category = 1 AND (category = 2 OR category = 3)");

Upvotes: 0

Related Questions