PHP 中的光标分页与列

Cursor Pagination in PHP with a Column

我正在使用 Laravel version 5.2。由于它有大量数据,我使用游标 pagiations 如下 table 具有 primary idname 字段

for page 1 -> select * from table LIMIT 10

For page 2 -> select * from table where id < $lastpagelastementID LIMIT 10

同理,如果我们按name列排序,那么这个cursor pagination怎么处理呢?
有什么选择吗?

我们可以使用 Laravel 中解释的分页

Laravel Pagination

但我需要如上所述的光标分页。谁能帮我找到解决办法?

您可以通过 composer 安装此包:

composer require juampi92/cursor-pagination

配置

将配置文件发布到 config/cursor_pagination.php 运行:

php artisan vendor:publish --provider="Juampi92\CursorPagination\CursorPaginationServiceProvider" --tag="config"

它是如何工作的

光标分页背后的主要思想是它需要一个上下文来知道接下来要显示什么结果。所以不是说 page=2,而是说 next_cursor=10。结果与老式页面分页相同,但现在您可以更好地控制输出,因为 next_cursor=10 应该始终 return 相同(除非删除某些记录)。

优点

  • 新行不会影响结果,因此分页时不会出现重复结果。
  • 通过索引游标过滤比使用数据库偏移快得多。
  • 使用上一个光标来避免重复第一个元素。

缺点

  • 没有上一页,虽然浏览器仍然有。
  • 不能导航到任意页面(您必须知道上一个结果才能知道下一个结果)。
  • 对查询生成器结果进行分页

    有多种方法可以对项目进行分页。最简单的方法是在 查询构建器 Eloquent 查询 上使用 cursorPaginate 方法。 cursorPaginate 方法自动负责设置适当的限制并根据用户正在查看的光标获取下一个或前一个元素。默认情况下,cursor 由 HTTP 请求中的页面查询字符串参数值检测。该值由考虑到您的自定义配置的包自动检测,并自动插入到分页器生成的链接和元数据中。

    public function index()
    {
        $users = DB::table('users')->cursorPaginate();
        return $users;
    }
    

    我认为这可能会解决您的问题。这是自定义分页

    在您的 Blade 视图文件中:

    <!-- pass variable page with a value 
         this generation of your pagination
         should be based to the number of rows
         of your table in the database and not
         static. use foreach for this.
    -->
    <a href="pagination?page=1">1</a>
    ...
    

    在您的控制器中:

    public function pagination(Request $request){
        // set the target page to 0 if page is 1 or null
        // else get the value 
        $targetPage = ($request->input('page') == 1 || !$request->input('page')) ? 0 : ($request->input('page') - 1) ;
        $noOfDataToGet = 10;      
    
        // get the number of data and skip the data based of target page * number of data        
        $tables = Tables::take($noOfDataToGet)->skip($targetPage * $noOfDataToGet)->get();
    }
    

    希望对您有所帮助