2013-04-05 80 views
0

我在模型下面的函數,如..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(); 

在這裏,我想用selectfrom和,你可以看到,但在運行第一get()後,查詢結束。那麼有沒有辦法做到這一點?或者我必須兩次寫入活動記錄?

我試圖這樣做的原因是在限制分頁total_rows配置之前得到num_rows

回答

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