簡體   English   中英

CodeIgniter:如何編寫 where_in OR where_in 查詢?

[英]CodeIgniter : how to write where_in OR where_in query?

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

所以基本上我想做: where_in OR 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 函數。

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

謝謝

是的, Codeigniter中有一個or_where_in函數。

示例

$arr_price=array(20,40,80,30);
$this->db->or_where_in('price', $arr_price);
//SQL Query: OR price IN(20,40,80,30);

語法:

or_where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])

參數:

$key (string) – The field to search
$values (array) – The values searched on
$escape (bool) – Whether to escape values and identifiers

返回:

DB_query_builder instance

返回類型:

object

生成一個 WHERE 字段 IN('item', 'item') SQL 查詢,如果合適的話用 'OR' 連接。 生成一個 WHERE 字段 IN('item', 'item') SQL 查詢,如果合適的話用 'OR' 連接。

如果需要更多幫助,我很樂意提供幫助。 快樂編碼。

我不確定這是否是您想要的:

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

當您使用“左”連接時,無論如何都不要使用“where條件”作為or_where_inwhere_in因為如果未找到,它將為該左查詢創建 array() 。

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

暫無
暫無

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

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