2015-03-19 162 views
3

我試着通過活動記錄,以使笨查詢:如何在CI中使用OR和AND運算符進行查詢?

if (isset($data['where']['and'])) { 
    $this->db->where($data['where']['and']); 
} 

if (isset($data['where']['or'])) { 
    $this->db->or_where_in('idSpec', $data['where']['or']); 
} 

我想:

WHERE name = 1 AND (idSpec = 2 OR idSpec = 3 OR idSpec = 4); 

但現在我得到:

WHERE name = 1 OR idSpec = 2 OR idSpec = 3 OR idSpec = 4; 
+0

你確定你的查詢產生'WHERE name = 1'? '$ data ['where'] ['and']';和'$ data ['where'] ['或']'包含了什麼? – 2015-03-19 13:27:17

回答

3

使用下面的代碼。

if (isset($data['where']['and'])) { 
     $this->db->where($data['where']['and']); 
    } 
    if (isset($data['where']['or'])) { 
     $this->db->where("(idSpec = 2 OR idSpec = 3 OR idSpec = 4;)", NULL, FALSE); 
    } 
+0

而不是'idSpec = 2或idSpec = 3或idSpec = 4;'我可以指定數組嗎? – Chaps 2015-03-19 12:31:11

2

我假設你的$data['where']['or']包含一些ID。
這可能會幫助你。

if (isset($data['where']['or'])) 
{ 
    $or_conditions='(idSpec ='.implode(' OR idSpec = ',$data['where']['or']).')'; 
    $this->db->where($or_conditions);//if this produce error use bellow one 
    //$this->db->where($or_conditions,'',false); 
} 
0

這是選擇從我使用好長一段時間的數據庫數據的基本方法..

/** 
* Le wild function to make a life better. 
* Doing abrakadabra 
* 
* @param  $table 
* @param bool $selector 
* @param string $order 
* @param bool $start 
* @param bool $limit 
* @param  $return 
* 
* @return mixed 
*/ 

public function _getCustomTableData($table, $selector = FALSE, $order = 'id DESC', $start = FALSE, $limit = FALSE, $return = FALSE, $group_by = FALSE) 
{ 
    $query = $return ? $this->db->select($return) : $this->db->select('*'); 

    if ($selector) { 
     if (isset($selector['mixed_selection']) && $selector['mixed_selection'] == TRUE) { 
      $query = $this->db->where($selector['mixed_selection']); 
     } else { 
      foreach ($selector as $select_array): 
       $query = $this->db->where($select_array); 
      endforeach; 
     } 
    } 

    if ($group_by) { 
     $query = $this->db->group_by($group_by); 
    } 

    $query = $this->db->order_by($order); 
    if ($start && $limit) { 
     $query = $this->db->limit($limit, $start); 
    } 
    if (! $start && $limit) { 
     $query = $this->db->limit($limit); 
    } 

    // proceed 
    $query = $this->db->get($table); 

    if ($limit == TRUE && $limit == 1) { 
     $query = $query->row_array(); 
     if ($return) { 
      return $query[$return]; 
     } else { 
      return $query; 
     } 
    } else { 
     $query = $query->result_array(); 
     return $query; 
    } 

} 

和查詢的樣子:

$this->_getCustomTableData('table', array(array('selector' => '1', 'time >=' => time())), 'id DESC', FALSE, 1, 'id'); 

它像:

SELECT 'id' FROM `table` WHERE `selector` = 1 AND `time` >= 1472582... ORDER BY id DESC LIMIT 1 

或者您可以使用「混合自選ection「

$this->_getCustomTableData('table', array('mixed_selection' => 'selector = 1 AND time >= 1472582...'), 'id DESC', FALSE, 1, 'id'); 

並且結果將是相同的。我已經寫了這種方法,當我初學CI,它幫了我很多:)

相關問題