chelout/offset-pagination

为Laravel简化偏移分页

v1.2 2019-07-05 12:10 UTC

This package is auto-updated.

Last update: 2024-08-29 05:05:41 UTC


README

此包提供了基于偏移量的分页功能,已与Laravel的查询构建器Eloquent ORM集成。它会自动检查请求的GET参数来计算SQL查询限制,并为您自动构建下一页和上一页的URL。

安装

您可以使用composer安装此包:

composer require chelout/offset-pagination

此包将自动注册自己。

配置

要发布配置文件到config/offset_pagination.php,请运行:

php artisan vendor:publish --provider="Chelout\OffsetPagination\CursorPaginationServiceProvider" --tag="config"

这将发布以下文件。您可以自定义默认每页项目数和最大每页项目数。

基本用法

分页查询构建器结果

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

分页Eloquent结果

$users = User::offsetPaginate(5);

当然,您可以在设置查询的其他约束(如where子句)后调用paginate。

$users = User::where('votes', '>', 100)->offsetPaginate(5);

排序结果

$users = User::orderBy('id', 'desc')->offsetPaginate(5);

显示分页结果

转换为JSON

基本返回将分页器转换为JSON,输出结果如下:

Route::get('api/v1/users', function () {
    return App\User::offsetPaginate();
});

调用api/v1将输出:

{
   "data": [
        {}, 
   ],
    "offset": 60,
    "offset": 60,
    "prev": 55,
    "next": 65,
    "limit": 5,
    "total": 100,
    "next_page_url": "https://example.com/api/v1/users?limit=5&offset=65",
    "prev_page_url": "https://example.com/api/v1/users?limit=5&offset=55"
}

使用资源集合

默认情况下,当Laravel的API资源作为集合使用时,它们会将分页器的元数据输出到linksmeta

    {
        "data":[
            {}, 
        ],
        "links": {
            "first": "https://example.com/api/v1/users",
            "last": "https://example.com/api/v1/users?offset=95",
            "prev": "https://example.com/api/v1/users?offset=55",
            "next": "https://example.com/api/v1/users?offset=65"
        },
        "meta": {
            "offset": 60,
            "prev": 55,
            "next": 65,
            "limit": 5,
            "total": 100
        },
    }

测试

使用以下命令运行测试:

vendor/bin/phpunit

鸣谢

许可

MIT许可(MIT)。有关更多信息,请参阅许可文件