【问题标题】:Group multiple condition logic with CodeIgniter's ActiveRecord使用 CodeIgniter 的 ActiveRecord 对多个条件逻辑进行分组
【发布时间】:2015-02-08 08:24:35
【问题描述】:

我需要使用 CodeIgniter 运行条件为 whereor_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 子句,则不遵守其他条件。如何对引用$degree的条件进行分组?

【问题讨论】:

  • 我发现您的问题对于所需的确切 sql 含糊不清。请通过表达您需要的确切 sql 来完成此问题。此外,!empty() 的使用似乎也不合适。为什么第一次访问时检查$degree是否存在,但第二次访问变量时却不保证变量存在。这很奇怪……或者是错误的。解决方法是使用group_start()group_end(),但问题是你的问题太模糊,无法自信地回答。

标签: php codeigniter activerecord grouping multiple-conditions


【解决方案1】:

你的代码应该是这样的:

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-&gt;db-&gt;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);
}

【讨论】:

  • 实际上我需要 or_where_in 子句应该只比较前面的条件,表示列 Education & Education1
  • 我就是这么做的,不是吗?
  • 我不支持这些sn-ps。使用多个!empty()|| 检查意味着如果存在任何 个变量,则将尝试查询——但逻辑应该 是所有变量都是!empty()
【解决方案2】:

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

  • 将此查询的逻辑移至数据库端。创建一个存储过程并将所有参数传递给它,并根据传递给它的值根据需要在此处构建选择语句(包括所有列等)。而从 PHP 端(来自 Codeigniter)只需调用这个存储过程来获得你需要的东西。
  • 用 PHP 编写一个原始查询,然后使用 Codeigniter 的“查询”功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2017-07-28
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    相关资源
    最近更新 更多