hanksie / laravel-cursor-paginator-through-when-serialize
为序列化时转换分页数据添加一个注册回调的方法
Requires (Dev)
- orchestra/testbench: 6.x-dev
- phpunit/phpunit: 9.5.x-dev
This package is auto-updated.
Last update: 2024-09-30 01:49:01 UTC
README
为什么创建这个包
当使用 AbstractCursorPaginator::through()
或 AbstractCursorPaginator::getCollection()->transform()
来转换每个项目,并且序列化(例如 toArray(), toJson())隐式或显式地将给出一个错误:未定义索引
,Paginate 和 SimplePaginate 没有这个问题。
这个错误发生在 AbstractCursorPaginator::getParametersForItem()
当分页有上一页或下一页时,该方法将被调用。错误发生是因为 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()
方法。