Welcome Guest, Not a member yet? Register   Sign In
Parenthesis in ActiveRecord queries ?
#1

[eluser]oll[/eluser]
Hello,

I have a videos table with fields like 'title', 'owner', 'description'.
I have a little search engine that does a simple research ($search string) amongst these fields.

Code:
$fields = array('title','owner','description');
foreach ($fields as $field) {
  $this->db->or_like($field,$search);
}

It works.

But now, I need to secure my site. Each video belongs to one group (the table contains a 'group' field). An authenticated user belongs to several group ($groups array). And I want the search engine to display only the videos if he belongs to the group.
So, I simply added a IN statement :

Code:
$fields = array('title','owner','description');
foreach ($fields as $field) {
  $this->db->or_like($field,$search);
}
$this->db->where_in('group',$groups);

A query looks like :

SELECT * FROM (`videos`) WHERE `groupe` IN ('public','linux','admin') AND `title` LIKE '%bird%' OR `owner` LIKE '%bird%' OR `description` LIKE '%bird%'

But since AND has higher precedence than OR, it's exactly the same as :

SELECT * FROM videos WHERE ( groupe IN (public,linux,admin) AND title LIKE bird ) OR owner LIKE bird OR description LIKE bird

And I want of course :

SELECT * FROM videos WHERE groupe IN (public,linux,admin) AND ( title LIKE bird OR owner LIKE bird OR description LIKE bird )


Is there an elegant way to have this result using CI active record queries ? I just need to add a couple of parenthesis.
Or, at least, is there a way I can get the generated query, instead of running it ? For instance, something like :
Code:
$part1 = $this->db->display_or_like($field,$search);
$part2 = $this->db->display_where_in('group',$groups);

So that I can do something like :
Code:
$query ="(".$part1.")".$part2;

Thank you.


Messages In This Thread
Parenthesis in ActiveRecord queries ? - by El Forum - 02-13-2009, 11:08 AM
Parenthesis in ActiveRecord queries ? - by El Forum - 03-15-2009, 04:42 AM
Parenthesis in ActiveRecord queries ? - by El Forum - 03-16-2009, 08:30 AM
Parenthesis in ActiveRecord queries ? - by El Forum - 03-19-2009, 07:37 AM
Parenthesis in ActiveRecord queries ? - by El Forum - 07-13-2010, 04:12 PM
Parenthesis in ActiveRecord queries ? - by El Forum - 08-26-2010, 11:51 PM



Theme © iAndrew 2016 - Forum software by © MyBB