6

I have a query the conditions of it below (minus select, from, etc)

$this->db->where('show_year', $yyyy);
$this->db->or_where('idn', $idn);
$this->db->or_like('post_slug', $idn);

which forms

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' 
OR `idn` = 'the' 
AND `post_slug` LIKE '%the%'

However I am looking to have it be more like

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' 
AND (`idn` = 'the' OR `post_slug` LIKE '%the%')

My problem is Im not sure if CI's active record supports this notion, and if it does, how would I tackle it, as I can't find notion of it anywhere in the docs. No matter how I change up the like, or_like, where, or_where I can't even nail something similar. So anyone got any ideas? I'd prefer to stay away from a raw query if at all possible, but if I have to prepare one and do it that way, I will, just prefer not to.

2
  • I think this answer might help, stackoverflow.com/questions/11937867/… just throw the (...) part inside one $this->db->where() call as a string (with the ()s) Commented Nov 18, 2012 at 10:28
  • I think you may be on to something with that one. Was hoping there was a means of having it remain broken down in parts to make it easier to change in time as its refined, and run down the line that builds the whole query out in its entirety through random conditions but if this be the only case Ill take it, good find Commented Nov 18, 2012 at 10:31

1 Answer 1

2

Did you try this?

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' AND `idn` = 'the' 
OR `show_year`='2009' AND `post_slug` LIKE '%the%'

I think the following produces expression above:

$this->db->select(...)->from(...)->
where("show_year","2009")->where("idn","the")->
or_where("show_year","2009")->like("post_slug","%the%")
Sign up to request clarification or add additional context in comments.

2 Comments

Mixing AND and OR without parentheses is probably a bad idea from a readability/maintainability standpoint even if the distributivity works as intended now. Better play it safe and use DNF or CNF clauses.
I know but with CI's AR can't do parentheses. It's only a(n ugly) workaround. Check the operator preference in mysql: dev.mysql.com/doc/refman/5.0/en/operator-precedence.html - mysql evalutes first AND after OR.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.