0

我的用户资源如下:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts()->paginate(10)),
    ];
}   

在 User 模型中,有 hasMany 关系posts

我的分页问题,​​post paginate 的链接和元并没有显示只获得 10 个没有分页链接的帖子

我的控制器

$user = User::query()
    ->where('id', $userId)
    ->with('posts')
    ->firstOrFail();

return new UserResource($user);
4

2 回答 2

0

Laravel 不会为您处理这种情况。

你只有两个选择:

  1. 编写自定义分页逻辑
  2. 只需在帖子 API 中使用两个具有专用分页的不同 API(推荐)
于 2021-07-13T14:56:17.493 回答
0

我认为这是因为您将posts属性作为集合而不是分页返回。

尝试

return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => $this->posts()->paginate(10),
    ];
于 2021-07-14T07:34:11.857 回答