如何在CI中使用OR和AND运算符进行查询?

时间:2015-03-19 11:50:10

标签: php codeigniter

我尝试通过Active Records在Codeigniter中进行查询:

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;

3 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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);
}

答案 2 :(得分: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

或者您可以使用"混合选择"

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

结果将是相同的。当我初学CI时,我已经写过这个方法,它帮助了我很多:)