2016-10-10 48 views
0

我正在使用codeigniter來查詢數據庫,並且我需要有條件地比較where子句中的數組。Codeigniter where_in OR where_in

所以基本上我想這樣做:where_in或where_in取決於哪些數組中有數據。所以我會有一個user_id數組或一個area_id數組。

我不知道如何結合where_in比較。這是我需要修改的查詢:

public function get_checks_test($org_id,$users,$areas) { 
    // get todays date 
    $todays_date = date("Y-m-d"); 
    // build where array 
    $check_array = array('c.org_id =' => $org_id, 'c.status !=' => '0', 'c.due <=' => $todays_date); 
    // build query 
    $this->db->select('c.*,a.check_area_id,b.check_user_id,d.area_name,u.first_name,u.last_name'); 
    $this->db->order_by('c.due', 'asc'); 
    $this->db->where($check_array); 
    $this->db->where_in('user_id', $users); 
    $this->db->or_where_in('area_id', $areas); 
    $this->db->join('check_assigned_areas a','a.check_id = c.check_id','left'); 
    $this->db->join('check_assigned_users b','b.check_id = c.check_id','left'); 
    $this->db->join('areas d','d.area_id = a.check_area_id','left'); 
    $this->db->join('users u','u.id = b.check_user_id','left'); 
    $check_object = $this->db->get('checks c'); 
    return $check_object->result(); 
} 

我不認爲有一個or_where_in函數可以找到。

我可以這樣做嗎?還是我需要重新思考?

感謝

+0

請檢查這一個,如果它會幫助你.. http://stackoverflow.com/questions/21946311/codeigniter-or-where-in –

+2

http://www.codeigniter.com/user_guide/ database/query_builder.html?highlight = where_in#CI_DB_query_builder :: or_where_in – sintakonte

+0

「我不認爲有一個or_where_in函數可以找到。」但它是一個函數,既在@sintakonte指出的文檔中,也在整個Web上包括StackOverflow。 – tar

回答

6

是的,有在笨一個or_where_in功能。如果需要更多幫助,我很樂意提供幫助。

Thanx, 快樂編碼。

1

我不知道這是否是你想要什麼:

if(!empty($users)){ 
    $this->db->where_in('user_id', $users); 
} 
elseif(!empty($areas)){ 
    $this->db->where_in('area_id', $areas); 
} 
0

當你使用「左」加入時,在任何情況下都不要使用「where condition」作爲or_where_inwhere_in,因爲如果沒有找到它,它將爲該左查詢創建array()。

$this->db->join('users u', 'u.id = b.check_user_id and u.id=' . $users, 'left'); 
相關問題