【问题标题】:How do I structure data in a resource collection?如何在资源集合中构建数据?
【发布时间】:2019-12-20 16:49:51
【问题描述】:

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

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

return new PostCollection(Post::latest()->get()); 在 PostControllers 索引中看到,我得到:

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

后控制器

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 资源的数据?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    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,我需要添加一个 $collects 属性和我的 PostResource 的路径,如下所示:

    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,
            ];
        }
    
    }
    

    我在谷歌上搜索了几次如何做到这一点,我必须在文档中扫描了几次,但没有看到如何做到这一点。希望这会有所帮助。

    【讨论】:

    • 是的,您需要将资源发送到集合中,因为您正在收集一组资源。您问题中的toArray 方法必须是PostResource 中的toArray 方法。另一方面,最好不要将id 公开。您已经在使用 slug,通过使其独一无二,可以很好地进行查询。
    猜你喜欢
    • 2022-07-26
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多