2015-06-05 73 views
5

我正在開發一個cakephp項目,並且新增了cakephp。正如標題中所提到的,我需要將一個mysql查詢的結果集進行分頁,以便在視圖中顯示它們。如何在cakephp中對自定義查詢結果進行分頁

通過這種方式,我可以對來自「Asin」模型的結果進行分頁。

$this->paginate =array('Asin'=>array(
      'fields' => array('sku','fnsku'), 
      'conditions' => $marketplace, 
      'page' => 1, 'limit' => 20, 
      'order' => array('Asin.asin' => 'asc') 
     ) 
$data = $this->paginate('Asin',$criteria); 

我還需要一種方法來分頁查詢的結果集。

$resultset = $this->Asin->query("SELECT * FROM products INNER JOIN asins ON products.id=asins.id ORDER BY products.id"); 

如何添加分頁?

+0

請檢查提供是否有用的答案。謝謝。 –

回答

4

CakePHP中使用兩種方法來管理分頁查詢,是PAGINATE和paginateCount,它們分別用於獲取頁面的數據和記錄總數。爲了讓分頁能夠處理您的自定義查詢,我們需要在我們的模型文件中實現上述兩個函數,您希望將分頁功能用於自定義查詢。

public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {  
    $recursive = -1; 

    // Mandatory to have 
    $this->useTable = false; 
    $sql = ''; 

    $sql .= "Your custom query here just do not include limit portion"; 

    // Adding LIMIT Clause 
    $sql .= (($page - 1) * $limit) . ', ' . $limit; 

    $results = $this->query($sql); 

    return $results; 
} 

....

public function paginateCount($conditions = null, $recursive = 0, $extra = array()) { 

    $sql = ''; 

    $sql .= "Your custom query here just do not include limit portion"; 

    $this->recursive = $recursive; 

    $results = $this->query($sql); 

    return count($results); 
} 

然後終於在控制器動作

// Do not forgot to set this, not sure why 
$this->Asin->recursive = 0; 

// Setting up paging parameters 
$this->paginate = array('Asin'=>array('limit'=>5)); 

// Getting paginated result based on page # 
$this->set('userData', $this->paginate('Asin')); 
+0

這不適用於連接,我沒有用普通查詢來檢查。 – urfusion