我在CodeIgniter中编写了一个活动记录查询,然后我意识到我需要将OR与to WHERE子句一起使用。所以我查阅了文档,找到了我想要的or_where。但当我使用它时,它在输出中产生AND。我找不到关于这个问题的任何其他问题。
我正在使用CodeIgniter:2.1.0
这是我的代码(略有删减):
$this->db->select("p.*",false);
$this->db->from('projects p');
$this->db->join('customers c', 'p.c_id = c.c_id','left outer');
if(isset($options['add_root']))
$this->db->or_where('p.p_id=',1,FALSE);
//Get top level projects by default (1) or whatever parent is specified.
if(isset($options['p_id']))
$this->db->where('p.p_id=',$options['p_id'],false);
$query = $this->db->get();//query
我认为您不需要or_where
。我认为你需要在PHP中使用更好的if/else。
你可能想要的逻辑:
if(isset($options['p_id']))
{
// if p_id is set, then look for p_id
$this->db->where('p.p_id=',$options['p_id'],false);
// if p_id and add_root are set, then look for p_id OR p_id = 1
if(isset($options['add_root']))
$this->db->or_where('p.p_id=',1,FALSE);
}
elseif(isset($options['add_root']))
{
// look for p_id = 1 only
$this->db->where('p.p_id=',1,FALSE);
}
因为or_where
是第一个,所以它只是默认为where
,然后后续的where
是默认值:一个"answers"。
你也可以用一系列elseif
来写上面的内容,但我认为这不太清楚:
if(isset($options['p_id']) && isset($options['add_root']))
$this->db
->where('p.p_id=',$options['p_id'],false)
->or_where('p.p_id=',1,FALSE);
elseif(isset($options['p_id']) || isset($options['add_root']))
$this->db
->where('p.p_id=',
// if add_root is set, then 1, otherwise p_id
(isset($options['add_root'])?1:$options['p_id']),false);
您试图运行的查询的顺序有一个小错误。您可以添加多个"where"子句,这些子句将转换为中间带有"AND"的查询。但如果你想用"OR"代替,你可以用"OR_where"。
在您的查询中,您使用了一个"or_where"子句,这是正确的,但在这之后您使用了"where",这实际上是上一个查询的总和。因此,您必须先使用"where"子句,然后使用"or_where"子句。
只要改变顺序就行了。