hanksie/laravel-cursor-paginator-through-when-serialize

为序列化时转换分页数据添加一个注册回调的方法

v0.1.0 2022-09-02 09:12 UTC

This package is auto-updated.

Last update: 2024-09-30 01:49:01 UTC


README

test

为什么创建这个包

当使用 AbstractCursorPaginator::through()AbstractCursorPaginator::getCollection()->transform() 来转换每个项目,并且序列化(例如 toArray(), toJson())隐式或显式地将给出一个错误:未定义索引,Paginate 和 SimplePaginate 没有这个问题。

这个错误发生在 AbstractCursorPaginator::getParametersForItem()

https://github.com/laravel/framework/blob/bdc707f8b9bcad289b24cd182d98ec7480ac4491/src/Illuminate/Pagination/AbstractCursorPaginator.php#L218

当分页有上一页或下一页时,该方法将被调用。错误发生是因为 AbstractCursorPaginator 需要一个字段来获取页面游标。例如,我们有一个用户模型,它包含 'id' 和 'name' 字段。我们调用 User::cursorPaginate(n) 来获取 CursorPaginator 实例,当分页器序列化时,AbstractCursorPaginator::getParametersForItem() 被调用。请参阅上面的源链接,$item 是一个用户模型实例如 { id: 1, name: 'someone', ...},回调块中的 $parameterName 是 "user.id",结果是 'id'

$item[$parameterName] ?? $item[Str::afterLast($parameterName, '.')]
// $item doesn't have key named 'user.id', so run next, get the user's id

如果在转换分页项目时,因为无法访问现有键,我们将给出一个错误:未定义索引: id

// $item: {extra_field: '...', origin: [user instance]}
$item[$parameterName] ?? $item[Str::afterLast($parameterName, '.')]
// $item doesn't have key named 'user.id', so run next, but $item doesn't have key named 'id' either. give an error: `Undefined index: id`

包是如何修复这个问题的

重写 Illuminate\Pagination\AbstractCursorPaginator::through() 以在序列化时注册一个回调,将项目切片中的每个项目映射到 "data" 字段。它之所以有效,是因为它没有改变原始 $items,它可以避免未定义索引错误。

如何使用

只需像以前一样使用 through() 方法。