views:

45

answers:

1

Hi all, I'm having some issues getting codeigniter active record to produce a query like this:

SELECT fruits.* FROM fruits
WHERE fruits.color = 'red'
AND ( fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7 );

Basically I want to have several or clauses but one where clause that is always enforced.

$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );
$this->db->where( 'fruits.color', 'red' );
$this->db->or_where( 'fruits.size', 'medium' );
$this->db->or_where( 'fruits.name', 'kiwi' );
$this->db->or_where( 'fruits.length', 7 );

Produces something like:

SELECT fruits.* FROM fruits WHERE fruits.color = 'red' OR fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7;

I need to enforce that color is always red.

Is there a decent way to do this?

A: 

There is no way to achieve this properly using CodeIgniter Active Record.

The only way that's not too ugly is using a custom string with the where() function like this:

$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );
$where = "fruits.color = 'red' AND ( fruits.size = 'medium' OR fruits.name = 'kiwi' OR fruits.length = 7 );";
$this->db->where( $where );

IMPORTANT: note that using a custom string, your variable WILL NOT be escaped, thus, you need to use $this->db->escape()

$this->db->select( 'fruits.*' );
$this->db->from( 'fruits' );

$color = 'red';
$size = 'medium';
$name = 'kiwi';
$length = 7;
$where = "fruits.color = '".$this->db->escape($color)."' AND ( fruits.size = '".$this->db->escape($size)."' OR fruits.name = '".$this->db->escape($name)."' OR fruits.length = '".$this->db->escape($length)."');";
$this->db->where( $where );

Edit:

I got confused on the good query, I corrected it :)

Weboide
Yeah, this is what I figured. Unfortunately my actual query has a bunch of or_where_in rather than just or_where.... so if I build a custom where string I might as well just write the whole query in raw SQL at that point :/Thanks for the input.
Anon
This was one the drawback of CodeIgniter, especially now that I use Yii which is pure OOP, I notice it even more.Otherwise a solution would be to create your own function to handle this, or to override the db class.
Weboide