Codeigniter中的多个or_where条件

时间:2014-12-10 08:04:41

标签: codeigniter

我需要使用codeigniter运行where和or_where条件的查询。代码,

$this->db->select('*');
    $this->db->from('registration');
    $this->db->where('MemberStatus',1);
    $this->db->where('Gender', $gender);
    if(!empty($city))
    $this->db->where_in('City',$city);
    if(!empty($education_sector))
    $this->db->where_in('education_sector',$education_sector);
    if(!empty($degree))
    $this->db->where_in('Education',$degree);
    $this->db->or_where_in('Education1',$degree);

上面的代码执行像

这样的查询
SELECT * FROM (`registration`) WHERE `MemberStatus` = 1 AND `Gender` = '1' AND (Age BETWEEN "18" AND "30") AND `Education` IN ('BCom', 'MCom') OR `Education1` IN ('BCom', 'MCom') 

如果他们读取or_where子句其他条件不起作用。我怎样才能将学位课程分组。请给我任何解决方案。

提前致谢

2 个答案:

答案 0 :(得分:0)

您的代码应该是这样的:

if(!empty($gender) || !empty($age) || !empty($city) || !empty($degree) || !empty($education_sector))
{
    $this->db->select('*');
    $this->db->from('registration');
    $this->db->where('MemberStatus',1);
    $this->db->where('Gender', $gender);
    $this->db->where($age >= 18);
    $this->db->where($age <= 30);
    $this->db->where_in('City',$city);
    $this->db->where_in('education_sector',$education_sector);
    $this->db->where_in('Education',$degree);
    $this->db->or_where_in('Education1',$degree);
}

修改 - 1:

这很复杂。您需要UNION来实现您的目标。很遗憾,CI Active Records不支持UNION,因此您必须使用$this->db->query()函数来编写查询。

会是这样的:

if(!empty($gender) || !empty($age) || !empty($city) || !empty($degree) || !empty($education_sector))
{
    $q = "(SELECT * FROM registration 
    WHERE MemberStatus = 1 
    AND Gender = '$gender'
    AND Age BETWEEN (18,30)
    AND City IN ('$city')
    AND education_sector IN ('$education_sector'))
    UNION
    (SELECT * FROM registration
    WHERE Education IN ('$degree')
    OR Education1 IN ('$degree'))";
    $this->db->query($q);
}

答案 1 :(得分:0)

在这种情况下,我会建议以下两种解决方案中的第一种:

  • 将此查询的逻辑移至数据库端。创建一个存储过程并将所有参数传递给它,并根据传递给此构建的值,在那里根据需要使用select语句(包含所有列等)。从PHP端(来自Codeigniter)只需调用此存储过程即可获得所需内容。
  • 在PHP中编写原始查询,只使用Codeigniter的“查询”功能。