CodeIgniter Active记录多个“where”和“or”语句

时间:2013-09-20 21:17:37

标签: php codeigniter

我有以下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"其中"声明。我想出的解决方案是......

//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();
}

这样可以正常使用,但有没有办法在不重复代码的情况下执行此操作?

2 个答案:

答案 0 :(得分:12)

我找到了解决方案!

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();
}

答案 1 :(得分:1)

我偶然发现了这一点,并希望添加以下解决方案,该解决方案使用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();
}
相关问题