【问题标题】:CodeIgniter Active Record multiple "where" and "or" statementsCodeIgniter Active Record 多个“where”和“or”语句
【发布时间】:2013-09-26 09:18:55
【问题描述】:

我有以下 Active Record 查询。

//Example 1
public function info($school, $class, $student, $keyword)
{
    $this->db->where('school.id', $school);
    $this->db->where('class.id', $class);
    $this->db->where('student.id', $student);

    $this->db->or_where('school.description', $keyword);
    $this->db->or_where('class.description', $keyword);
    $this->db->or_where('student.description', $keyword); 

    return $this->db->get('info')->result();
}

我想将底部的 3 个“or_where”语句分组,以便它们包含在顶部的 3 个“where”语句中。我想出的解决方案是这样的......

//Example 2
public function info($school, $class, $student, $keyword) 
{
    $this->db->where('school.description', $keyword);
    $this->db->where('school.id', $school);
    $this->db->where('class.id', $class);
    $this->db->where('student.id', $student);

    $this->db->or_where('class.description', $keyword);
    $this->db->where('school.id', $school);
    $this->db->where('class.id', $class);
    $this->db->where('student.id', $student);

    $this->db->or_where('student.description', $keyword); 
    $this->db->where('school.id', $school);
    $this->db->where('class.id', $class);
    $this->db->where('student.id', $student);

    return $this->db->get('info')->result();
}

这很好用,但是有没有办法在不重复代码的情况下做到这一点?

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    我找到了解决办法!

    public function info($school, $class, $student, $keyword)
    {
        $this->db->where('school.id', $school);
        $this->db->where('class.id', $class);
        $this->db->where('student.id', $student);
    
        $this->db->where("(school.description LIKE '$keywords' OR class.description LIKE '$keywords' OR student.description LIKE '$keywords')");
    
        return $this->db->get('info')->result();
    }
    

    【讨论】:

    • $keywords 可能是sql注入,需要先转义...例如。 $this->db->e​​scape_like_str($search)
    【解决方案2】:

    我只是偶然发现了这个并想添加以下解决方案,它使用 CI 活动记录 $this->db->like() 语法:

    public function info($school, $class, $student, $keyword)
    {
    
        $this->db->where('school.id', $school);
        $this->db->where('class.id', $class);
        $this->db->where('student.id', $student);
    
        $this->db->like('school.description', $keyword);
        $this->db->or_like('class.description', $keyword);
        $this->db->or_like('student.description', $keyword);
    
        return $this->db->get('info')->result();
    }
    

    【讨论】:

    • 上面没有对 LIKE 条件进行分组——因此,它不等于@Staysee 接受的解决方案。不幸的是,括号(告诉 MySQL 在 AND 中嵌套 OR)不能在 Active Record 语句中表达。
    猜你喜欢
    • 2014-12-24
    • 1970-01-01
    • 2015-09-17
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多