Codeigniter:从查询中提取部分数据

Codeigniter: Extract partial data from a query

我有个小问题请教: 假设我有一个很长的查询:

$this->db->select('*')
     ->from('x')
     ->join(...)
     ->where('y >',$id)
     ->where('z <',$nr)
     ->where(...)
     ...

我如何将所有 where 语句放入不同的变量中,以便我可以单独使用它们但只使用一个查询? 谢谢。

您需要创建不同的模型方法。每个方法都应该有 where 查询输出结果。在您的控制器中,您调用这些方法中的每一个并将结果存储在变量中。 为什么不这样做:

控制器:

function controller_method(){
    $res1 = $this->model_name->get_where_results1($id, $nr);
    $res2 = $this->model_name->get_where_results2($id, $nr);
    $res3 = $this->model_name->get_where_results3($id, $nr);
}

型号:

function get_where_results1($id, $nr) {
    $this->db->select('*')
            ->from('x')
            ->join("")
            ->where("");
    $query = $this->db->get();
    return $query->result();
}
function get_where_results2($id, $nr) {
     $this->db->select('*')
            ->from('x')
            ->join("")
            ->where("");
    $query = $this->db->get();
    return $query->result();
}
function get_where_results3($id, $nr) {
     $this->db->select('*')
            ->from('x')
            ->join("")
            ->where("");
    $query = $this->db->get();
    return $query->result();
}

更新 - 如果你想使用过滤器,我会这样:

控制器:

function controller_method() {
    $res1 = $this->model_name->model_method($filters);
}

型号:

function model_method($filters) {
    $this->db->select('*');
    $this->db->from('x');
    $this->db->join("");
    if ($filters['filt1']) {
        $this->db->where("something", $filters['filt1']);
    }
    if ($filters['filt2']) {
        $this->db->where("something", $filters['filt2']);
    }

    $query = $this->db->get();
    return $query->result();
}