簡體   English   中英

CodeIgniter Active記錄多個“where”和“or”語句

[英]CodeIgniter Active Record multiple “where” and “or” statements

我有以下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();
}

這工作正常,但有沒有辦法在不重復代碼的情況下執行此操作?

我找到了解決方案!

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

我只是偶然發現並想要添加以下解決方案,它使用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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM