根据用户选择,我需要在查询中过滤结果,但我仍然坚持如何在AND之后正确实现动态OR语句。我目前在CodeIgniter中使用Active Record,但这可能需要改变。
我基本上需要创建以下代码段:“WHERE city.id = 9 AND(eventType = 8或eventType = 9)”
我的代码目前如下:
$this->db->where('city.id =', $cityID);
if ($eventTypes != NULL){
foreach ($eventTypes as $item){
$eventTypeID = intval($item);
$this->db->or_where('eventtype.id =', $eventTypeID);
}
}
这会产生:WHERE city.id
= 13 OR eventtype.id
= 6 OR eventtype.id
= 8 ...所以我需要AND(
答案 0 :(得分:1)
Codeigniter的“ActiveRecord”(airquotes ...)类相当有限,并且对于更高级的AND
/ OR
范围界定效果不佳,并指回原始sql用于“更高级”的查询。
我会制定您自己的WHERE
字符串来构建您想要的特定查询,然后使用
$this->db->where($sql)
...示例
$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);