2010-11-04 74 views
6

我對kohana的分頁工作原理感到迷茫3.在任何地方Kohana 3都有分頁的好例子嗎?Kohana 3分頁

回答

14
 // Get the total count of articles 
    $count = $this 
     ->_profil 
     ->articles 
     ->count_all(); 

    // Create the pagination object 
    $pagi = Pagination::factory(array(
     'items_per_page' => 4, 
     'total_items'  => $count, 
    )); 

    // Find actual articles 
    $articles = $this->_profil 
     ->articles 
     ->join_categories() 
     ->order_by('id','DESC') 
     ->limit($pagi->items_per_page) 
     ->offset($pagi->offset) 
     ->find_all(); 

,然後在視圖中,你只是做

echo $pagi; // ofc, after passing the Pagination object to view 

這裏會發生什麼事是分頁類用它查看的__toString()魔術方法來呈現,以顯示分頁所需的HTML。所有分頁參數都可以在創建對象時修改(在我們的例子中,傳遞適當的鍵到傳遞給factory()方法的數組)。

分頁的默認鍵是「page」(查詢字符串),您也可以修改它。分頁還有一個默認配置,您可以通過將其複製到應用程序/配置文件夾來覆蓋它。

使用它:)

+1

也ORM具有有用'count_last_query(),用於計數結果行'方法。 – biakaveron 2010-11-05 19:40:02

+1

儘管在複雜查詢時我不會太依賴這種方法:)通過這種方式,我們可以重新使用計數查詢,並在計數發生前添加重置(FALSE)。 – Kemo 2010-11-05 21:28:16

+0

酷!這很有用,謝謝! – dana 2011-03-19 13:21:46

3

在Kohana 3.1分頁不包括在內。下載模塊並將其放入模塊文件夾中。啓用應用程序中的模塊/ bootstrap.php。這是我的控制器頁面。對於進一步的配置從模塊複製所提供的配置文件/分頁/配置/ pagination.php的application/config/pagination.php

$per_page =2; 
    $page_num = $this->request->param('page', 1); 
    $offset = ($page_num - 1) * $per_page; 
    $view =View::factory('image/imagelist')->bind('page_links',$page_links)->bind('results', $results)->bind('pagination', $pagination); 

    // Get the total count of records in the database 
    $userid = Auth::instance()->get_user()->pk(); 
    $count=ORM::factory('user_image')->where('app_userid','=',$userid)->count_all(); 


    // Create an instance of Pagination class and set values 
    $pagination = Pagination::factory(array( 

     'total_items' => $count, 
     'current_page' => array('source' => 'image/imagelist', 'key' => 'page'), 
     'items_per_page' => $per_page, 
     'offset' => $offset, 
     'view' => 'pagination/basic' 
)); 


     // Load specific results for current page 
    $results = DB::select()->from('user_images') 
      ->where('app_userid','=',$userid) 
      ->order_by('image_id','ASC') 
      ->limit($pagination->items_per_page) 
      ->offset($pagination->offset)->execute(); 

$page_links = $pagination; 
$this->template->content=$view->render(); 

你可能會得到錯誤ErrorException [注意]:未定義的屬性:Request::$uri 。在分頁類(模塊)中。爲了解決固定它

使用Request::current()->uri()代替Request::current()->uri