2014-10-29 46 views
0

我試圖用笨的活動記錄做下面的SQL查詢:笨「其中」和「or_where」

SELECT * FROM USERS_OPTIONS WHERE user_id = 3 AND (option_id = 2 OR option_id = 5 OR option_id = 108 OR ....)

對於這一點,我在笨這段代碼,但它不是working:

$this -> db -> where("user_id", $user_id); 

foreach($options as $option){ 
    $this -> db -> or_where("option_id" , $option["id"] ); 
} 

$ options是一個數組,我存儲所有我需要的options_id。

如果我單獨嘗試2個querys中的任何一個,它們就會工作。但我無法混合這兩個條件。

我怎樣才能得到這個?提前致謝。

回答

3

您可以使用$this->db->where_in()

在生成where字段( '項目', '項目')的SQL查詢用and連接, 如果合適

$names = array('Frank', 'Todd', 'James'); 
$this->db->where_in('username', $names); 
// Produces: AND username IN ('Frank', 'Todd', 'James') 

在您的情況,您將擁有:

$this->db->where_in('option_id', $options) 
     ->get_where("your_table", array("user_id" => $user_id))->result(); 

文件:https://ellislab.com/codeigniter/user-guide/database/active_record.html

1
$this->db->select()->from('USERS_OPTIONS')->where("user_id $user_id AND (

// LOOP THROUGH PHP TO PRINT SOME THING LIKE or_where 

)); 
+0

downvoter請你解釋原因 – Pupil 2014-10-29 12:46:40

+0

Downvoter,請解釋。 – Pupil 2014-10-29 15:05:13

0

您應該嘗試$this->db->where_in();。首先收集所有選項ID &然後使用它是這樣的:

在生成where字段(「項目」,「項目」)的SQL查詢採用AND如果合適

$names = array('Frank', 'Todd', 'James'); 
$this->db->where_in('username', $names); 
// Produces: AND username IN ('Frank', 'Todd', 'James') 
0

請檢查下面的代碼,並且您不能使用活動記錄方法連接AND OR條件。

//Filtering by user 
$where_condition = "(user_id = '".$user_id."')"; 

//Filtering by options 
if(count($options)){ 

    $where_condition .= " AND ("; 

    foreach($options as $option){ 
     $where_condition .= "option_id = '".$option["id"]."' OR "; 
    } 

    $where_condition = substr($where_condition, 0, -3); //Remove last 3 characters OR with space 

    $where_condition = $where_condition. ")"; 

} 

//Select data     
$this->db->select('*'); 
$this->db->from("TABLE_NAME"); 
$this->db->where($where_condition); 
0

最後,這是我發現實現這一目標使用活動記錄的最好辦法:

有了這樣的數組:

$options = array (option_id1 , option_id2, ... , option_idn); 

$this -> db -> where("id_user", $id_user); 
$this -> db -> where_in("id_option" , $options ); 

這給我正是我想要的,這很清楚