评论收藏
class CommentsCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
CommentsController
public function index()
{
$post = Post::find(1);
return ['post'=> $post, 'comments' => new CommentsCollection(Comment::paginate(1))];
}
回复
"comments": {
"data": [
{
"id": 1,
"content": "First comment",
"post_id": 6,
"account_id": 1,
"created_at": "2018-03-07 02:50:33",
"updated_at": "2018-03-07 02:50:34"
}
]
}
当资源使用
::collection
时会发生这种情况方法甚至 ResourceCollection 作为数组的一部分返回。如果我们要删除数组并返回纯集合:
return new CommentsCollection(Comment::paginate(1))
一切正常,响应将包括 元 和 友情链接 .
为什么 API Resource(使用
collection
方法或 ResourceCollection)在数组中返回时不包含分页信息?
最佳答案
我遇到了这个问题并找到了解决方案检查以下链接以获取解决方案的详细说明
https://laracasts.com/discuss/channels/laravel/paginate-while-returning-array-of-api-resource-objects-to-the-resource-collection?reply=575401
简而言之,请检查以下解决问题的代码片段
$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
关于laravel - ResourceCollection 不包括分页链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49289379/