如何在不返回集合中id列的情况下实现Laravel的游标分页器?
以下查询:
'users' => User::cursorPaginate(15)
返回单个用户,如下所示:
{
"id": 1,
"uuid": "376bec76-9095-4510-a5ba-fea0f234c6cf",
"username": "alexanderhorner",
"password": "$2y$12$qMITOdMr2XdAq3EMKwc/WeB/db9IaQdkZ5egqY7CX5WpUwwHLKOLK"
}
现在,假设我有一个API。我希望api/v1/user
使用cursorPaginate()
返回相同的分页结果,但我不想返回id列。
'users' => User::select('uuid', 'username')->cursorPaginate(15)
将返回一个错误,因为cursorPaginate()
需要ID列或类似的内容:
InvalidArgumentException
Illegal operator and value combination.
解决这个问题的最好方法是什么?过滤cursorPaginate()
返回的集合
发布于 2021-09-29 00:19:39
您还可以检查Builder.php中的cursorPaginate实现(和签名)。有一个参数columns
。看看这个:
/**
* Get a paginator only supporting simple next and previous links.
*
* This is more efficient on larger data-sets, etc.
*
* @param int|null $perPage
* @param array $columns
* @param string $cursorName
* @param \Illuminate\Pagination\Cursor|string|null $cursor
* @return \Illuminate\Contracts\Pagination\CursorPaginator
*/
public function cursorPaginate($perPage = 15, $columns = ['*'], $cursorName = 'cursor', $cursor = null)
{
return $this->paginateUsingCursor($perPage, $columns, $cursorName, $cursor);
}
发布于 2021-09-28 10:33:05
您可以在作为响应返回之前映射用户模型集合。
通过执行以下操作,您可以将所需的属性映射到名为$users_to_be_returned
的新变量中,并在响应的属性中返回此属性。
您可以使用数组、stdClass甚至更好的DTO对响应结构执行任何操作。
$users = User::cursorPaginate(10);
$users_dtos = collect($users->items())->map(function ($user) {
$user_dto = new UserDTO(); // or even an stdClass object
$user_dto->username = $user->username;
$user_dto->password = $user->password;
return $user_dto;
})->toArray();
$response = new UserResponseDTO();
$response->users = $users_dtos;
$response->pagination_info = new PaginationInfoDTO();
$response->pagination_info->per_page = $users->perPage();
$response->pagination_info->path = $users->path();
$response->pagination_info->next_cursor = $users->nextCursor()->parameter('users.id');
$response->pagination_info->next_page_url = $users->nextPageUrl() ? $users->nextPageUrl() : null;
$response->pagination_info->previous_cursor = $users->previousCursor() ? $users->previousCursor()->parameter('users.id') : null;
$response->pagination_info->prev_page_url = $users->previousPageUrl() ? $users->previousPageUrl() : null;
return response()->json($response);
https://stackoverflow.com/questions/68415758
复制相似问题