Dynamic OR/AND in query
Based on user selections, I need to filter results in my query, but I'm stuck on how to correctly implement dynamic OR statements after my AND. I'm currently using Active Record in CodeIgniter, but this may have to change.
I essentially need to create the following snippet: "WHERE city.id = 9 AND (eventType = 8 or eventType = 9)"
- if there are no OR statements, then I don't need the AND
- there could be 1-n OR statements
My code currently is as follows:
开发者_运维技巧$this->db->where('city.id =', $cityID);
if ($eventTypes != NULL){
foreach ($eventTypes as $item){
$eventTypeID = intval($item);
$this->db->or_where('eventtype.id =', $eventTypeID);
}
}
This produces: WHERE city.id
= 13 OR eventtype.id
= 6 OR eventtype.id
= 8 ... so I need the AND (
Codeigniter's "ActiveRecord" (airquotes...) Class is fairly limited and doesn't do well with more advanced AND
/OR
scoping, and points you back to raw sql for "more advanced" queries.
I would formulate your own WHERE
string to build the specific query you are wanting and then just use
$this->db->where($sql)
example...
$where = "city.id = $cityID ";
if ($eventTypes != NULL)
{
$where .= "AND ( ";
foreach ($eventTypes as $i => $type)
{
$eventTypeID = intval($type);
// if it's not the first element
// (assumes $eventTypes is non-associative)
if ($i !== 0)
{
$where .= "OR ";
}
$where .= "eventtype.id = $eventTypeID ";
}
$where .= " ) ";
}
$this->db->where($where);
精彩评论