如何构造资源集合中的数据?

时间:2019-12-20 08:49:51

标签: laravel

我正在尝试构建资源集合的数据输出。通过分页,我得到:

  

未定义的属性:Illuminate \ Pagination \ LengthAwarePaginator :: $ id

使用return new PostCollection(Post::latest()->get());,如PostControllers索引所示,我得到了:

  

此集合实例上不存在属性[id]。

PostController

public function index()
{
    //return PostResource::collection(Post::latest()->paginate(1));

    return new PostCollection(Post::latest()->paginate(1));
}

PostCollection资源

class PostCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        //return parent::toArray($request);

        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'slug' => $this->slug,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,  
        ];
    }

}

注释掉的PostResource::collection()在相同的代码下可以很好地工作。如何构造我的PostCollection资源的数据?

1 个答案:

答案 0 :(得分:0)

  

The $this->collection property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailing Collection string.

简而言之,PostCollection从称为Post的单一资源继承结构。由于我的帖子资源名为PostResource,因此需要像我的PostResource的路径一样添加一个$collects属性:

class PostCollection extends ResourceCollection
{
    /**
     * The resource that this resource collects.
     *
     * @var string
     */
    public $collects = 'App\Http\Resources\PostResource';

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {

        return [
            'data' => $this->collection,
        ];
    }

}

我用谷歌搜索了几次,但是我必须在文档中扫描几次而不看如何做。希望这会有所帮助。