douchuo0730 2015-07-12 17:25
浏览 45
已采纳

如何分页可用收藏[Laravel 4.2]

Suppose I have 200 records in my DB. While displaying those records I want to paginate them. The normal approach would be doing something like

$tasks = Tasks::paginate(10); 

Then

$tasks->links();

That code works fine. However, With that code you are going to run DB query every time you fetch those 10 rows (200/10= 20 times for all rows).

What I need is to fetch all data at once, store them in a collection (say $tasks),Then paginate the resulting collection instead of fetching again from DB.

Even more, I need to query something like "Get only 100 records and paginate them by 10 " which would be nice if it would be something like

Tasks::take(100)->paginate(10) 

but unfortunately even that do not work.

Anyone with an idea on how to tackle these issues?

  • 写回答

1条回答 默认 最新

  • douyi5822 2015-07-12 17:41
    关注

    Laravel 5

    $tasks = Tasks::take(100); // fetch 100 tasks
    
    // initialize paginator
    $paginator = new \Illuminate\Pagination\Paginator($tasks, 10, $pageNumber); 
    
    // get current page of tasks
    $currentPage = $paginator->items();
    

    In order to get different pages of tasks you'll need to create new Paginator objects, as it doesn't store the whole collection of tasks but only current page.

    Laravel 4

    It seems that Paginator in Laravel 4 doesn't "handle the pagination", meaning it expects you to pass not all the items but only items from current page. In L5 you could pass all items and current page and Paginator would handle everything for you.

    In order to use the Paginator in L4 you'll need to slice the arra of tasks yourself and then use Paginator facade (that uses Illuminate\Pagination\Factory internally) to create Paginator object.

    use Paginator;
    
    $tasks = Tasks::take(100);
    $currentPageTasks = $tasks->slice(($currentPage - 1) * $perPage, $perPage);
    Paginator::make($currentPageTasks, $tasks->count(), $perPage);
    

    I'm not sure though if Paginator built this way will be of any use to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化