2015-03-02 50 views
1

我使用cakephp 2.5.6,我想在我的視圖文件中顯示數組。我嘗試將CakePHP默認分頁與此數組,但它不起作用。這裏是我的示例代碼如何將cakephp默認分頁數組

---'my_pages' controller----- 

public function view(){ 
    //some other code 
    $resultArray = $this->MyPages->getResults(); 
    $resultArray = $this->Paginator->paginate('resultArray'); 
    $this->set(compact('resultArray','rightPanel')); 
} 

和我的視圖文件

----- 'view.ctp' file ------ 
//some other code 

foreach ($resultArray as $result){ 
    echo $result['subject']; 
    echo $result['body']; 
} 

在我的情況下,該$resultArray有近百元素,我想把分頁此頁面上。那麼是否有可能在這種情況下使用cakephp默認分頁?謝謝:)

回答

1

您需要執行cakephp自定義分頁。

CakePHP中使用兩種方法來管理分頁查詢,是PAGINATE和paginateCount,它們分別用於獲取頁面數據,總 記錄數。要使用您的自定義 查詢進行分頁工作,我們需要在我們的 型號文件中實現上述兩個功能,您希望將分頁功能用於自定義查詢。 你也可以在你的行爲文件中實現。讓我們看看我們如何可以 有這個實現。

//in MyPages model add 

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

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

    $sql .= "SELECT * FROM table_name limit "; 

    // 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 .= "SELECT * FROM table_name"; 

    $this->recursive = $recursive; 

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

    return count($results); 
} 

你的控制器文件看起來象下面這樣:

---'my_pages' controller----- 

public function view(){ 
    // Do not forgot to set this, not sure why 
    $this->MyPages->recursive = 0; 
    // Setting up paging parameters 
    $this->paginate = array('MyPages'=>array('limit'=>5)); 
    // Getting paginated result based on page # 
    $this->set('resultArray', $this->paginate('MyPages')); 
} 

注:MyPages應該我的頁面,因爲CakePHP的型號名稱應爲單數。

您的視圖文件看起來象下面這樣:

----- 'view.ctp' file ------ 
//some other code 

foreach ($resultArray as $result){ 
    echo $result['subject']; 
    echo $result['body']; 
} 

你也可以閱讀Pagination with Custom Queries in CakePHP

+0

謝謝:),當我把你的答案它的工作。但鑑於每頁頁面項目不能正常工作,我嘗試了很多方法,但似乎不工作。使用調試器顯示分頁限制和其他變量是正確的。但當前頁面顯示9.不知道爲什麼是這樣,你有一個想法,爲什麼它的行爲是這樣的。 – indrarajw 2015-03-05 13:34:43