Src*_*Src 7 laravel laravel-5.5
评论集
class CommentsCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
Run Code Online (Sandbox Code Playgroud)
评论控制器
public function index()
{
$post = Post::find(1);
return ['post'=> $post, 'comments' => new CommentsCollection(Comment::paginate(1))];
}
Run Code Online (Sandbox Code Playgroud)
回复
"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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
当资源使用::collection方法甚至 ResourceCollection 作为数组的一部分返回时,就会发生这种情况。
如果我们要删除数组并返回纯集合:
return new CommentsCollection(Comment::paginate(1))
一切正常,响应将包括meta和links。
为什么 API Resource(使用collection方法或 ResourceCollection)在数组中返回时不包含分页信息?
小智 9
我遇到了这个问题并找到了解决方案,请查看以下链接以获取解决方案的详细说明
简而言之,检查以下解决问题的代码片段
$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
Run Code Online (Sandbox Code Playgroud)
我已经在本地检查过它,是的,你是对的,它不返回元和链接。所以我有一个有效的解决方案。创建帖子资源。以及您帖子的资源控制器。然后在您需要评论的单个帖子 api 上,只需显式返回您的评论即可。
class PostsResource extends Resource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'comments' => Comment::paginate(5)
];
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您的演出控制器代码意味着单个帖子将如下所示:
public function show($id)
{
return new PostsResource(Post::find($id));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2568 次 |
| 最近记录: |