【问题标题】:ResourceCollection doesn't include pagination linksResourceCollection 不包括分页链接
【发布时间】:2020-01-24 19:02:27
【问题描述】:

评论集合

class CommentsCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection
        ];
    }
}

评论控制器

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)在数组中返回时不包含分页信息?

【问题讨论】:

    标签: laravel laravel-5.5


    【解决方案1】:

    我遇到了这个问题并找到了解决方案,请查看以下链接以获取解决方案的详细说明

    https://laracasts.com/discuss/channels/laravel/paginate-while-returning-array-of-api-resource-objects-to-the-resource-collection?reply=575401

    简而言之,检查以下解决问题的代码sn-p

    $data = SampleModel::paginate(10);
    return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
    

    【讨论】:

      【解决方案2】:

      我注意到资源收集的结果必须单独返回才能正常工作

      return ItemMiniResource::collection(
              $items->paginate(10)
          );
      

      效果很好,但是

      $data['items'] = ItemMiniResource::collection(
              $items->paginate(10)
          );
      return $data
      

      不包括分页链接

      【讨论】:

        【解决方案3】:

        我已在本地检查过,是的,您是对的,它不会返回元数据和链接。所以我有一个可行的解决方案。创建一个帖子资源。以及您帖子的资源控制器。然后在需要 cmets 的单个 post api 上,显式返回您的 cmets。

        class PostsResource extends Resource
        {
            public function toArray($request)
            {
                return [
                    'id' => $this->id,
                    'title' => $this->title,
                    'body' => $this->body,
                    'comments' => Comment::paginate(5)
                ];
            }
        }
        

        所以你的节目控制器代码意味着单个帖子将是这样的:

        public function show($id)
        {
          return new PostsResource(Post::find($id));
        }
        

        【讨论】:

          猜你喜欢
          • 2013-06-14
          • 2018-01-16
          • 2019-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-21
          • 2020-11-09
          相关资源
          最近更新 更多