CodeIgniter:如何对以前的活动记录使用两次get()活动记录



我在模型下面设置了如下函数:

    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();

这里我想使用select, fromwhere与2 this->db->get(),你可以看到,但查询结束后运行第一个get()。有什么办法可以做到吗?还是需要写两次活动记录?

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

你可以这样做。

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);
    }
}   

最新更新