【问题标题】:CodeIgniter: How to use the get() active record twice with previous active records?CodeIgniter:如何将 get() 活动记录与以前的活动记录一起使用两次?
【发布时间】:2013-04-05 09:14:44
【问题描述】:

我在模型下有如下功能如图..

    public function get_products($category, $brand, $filter, $page, $limit) {
    // output
    $output = "";
    // offset
    $offset = $limit * ($page - 1);
    // query for pagination
    $this->db->select("*");
    $this->db->from("products");
    $this->db->where("category", $category);
    if ($brand != "all") {
        $this->db->where("brand", $brand);
    }
    // first time use
    $query = $this->db->get();
    $total_rows = $query->num_rows();
    $this->db->limit($limit, $offset);
    switch ($filter) {
        case 'latest':
        $this->db->order_by("released", "ASC");
        break;
        case 'most-viewed':
        $this->db->order_by("views", "ASC");
        break;
        case 'price-low-to-high':
        $this->db->order_by("price", "DESC");
        break;
        case 'price-high-to-low':
        $this->db->order_by("price", "ASC");
        break;
    }
    //second time use
    $query = $this->db->get();

在这里,我想使用selectfromwhere 和2 个this->db->get(),如您所见,但查询在运行第一个get() 后结束。那么有没有办法做到这一点?或者我必须写两次活动记录?

我尝试这样做的原因是在限制分页 total_rows 配置之前获取 num_rows

【问题讨论】:

    标签: codeigniter activerecord get


    【解决方案1】:

    你可以这样做。

    public function get_products($category, $brand, $filter, $page, $limit) 
    {
        $output = "";
        $offset = $limit * ($page - 1);
    
        $this->getQuery($category , $brand);
        $query = $this->db->get();
    
        $total_rows = $query->num_rows();
        //Call the query again 
        $this->getQuery($category , $brand);
        /*  This time limit and order will be applied to the query */   
        $this->db->limit($limit, $offset);
    
        switch ($filter) {
            case 'latest':
            $this->db->order_by("released", "ASC");
            break;
            case 'most-viewed':
            $this->db->order_by("views", "ASC");
            break;
            case 'price-low-to-high':
            $this->db->order_by("price", "DESC");
            break;
            case 'price-high-to-low':
            $this->db->order_by("price", "ASC");
            break;
        }
        //Run query now
        $query2 = $this->db->get();
    }
    /* This will only generate the query and will not run it */
    function getQuery($category , $brand){
    
        $this->db->select("*");
        $this->db->from("products");
        $this->db->where("category", $category);
        if ($brand != "all") {
            $this->db->where("brand", $brand);
        }
    }   
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2014-02-22
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多