8

我有以下活动记录查询。

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

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

4

2 回答 2

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();
}
于 2013-09-20T21:47:50.857 回答
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();
}
于 2014-12-04T11:55:16.403 回答