2013-04-05 21 views
1

我有一個函數根據傳遞的參數返回數據。 基本上,查詢根據子句進行更改。使用Codeigniter的活動記錄的條件從句

if(1==$case) 
return select()->from('db')->where('x',$something)->where('y','fixed')... 

else if(2==$case) 
return select()->from('db')->where('x','fixed')->where('y',$something)... 

有沒有更好的方法來做到這一點?

而且,是有可能有這樣的條款

...->where('category',*) 

「*」,以由一個值或一些其等於「任何」來代替。

回答

3

這種類型的查詢也稱爲「動態查詢」,因爲您可以以簡單的方式組合子句。試試這個:

$query = $this->db->select() 
    ->from('db'); 
if(1==$case) { 
    $query->where('x',$something) 
      ->where('y','fixed') 
} 
elseif (2==$case){ 
    $query->where('x','fixed') 
      ->where('y',$something) 
} 
.... 
return $query->get(); 

回答你的第二個問題,你可以使用:

$this->db->like('category', '%'); 
3

你可以不喜歡這個 -

$where = array(); 

if(1==$case) 
$where['x'] = $something; 
$where['y'] = 'fixed'; 

else if(2==$case) 
$where['x'] = $something; 
$where['y'] = 'fixed'; 

$this->db->where($where); 
$this->db->get(); 
1

你可能已經簡化了像這樣

if($case == 1){ 
    $this->db->where('x',$something)->where('y','fixed'); 
}else if($case == 2){ 
    $this->db->where('x','fixed')->where('y',$something) 
}else{ 
    //no where clause 
} 
$query = $this->db->get('db_table'); 
return $query->result();