使用keyby收集方法检索雄辩的api资源

时间:2019-09-30 12:46:48

标签: php laravel laravel-5 eloquent laravel-resource

我有一个终端API点

users/{user}

现在在用户资源中,我想返回

     public function toArray($request)
        {
            // return parent::toArray($request);

            return [
                'id' => $this->id,
                'name' => $this->name,
//                'comments' => $this->post->comments->keyBy('post_id')
                'comments' => new CommentCollection($this->post->comments->keyBy->post_id)

            ];
        }

CommentCollection类

public function toArray($request)
    {
        // return parent::toArray($request);

        return [
            'data' => $this->collection->transform(function($comment){
                return [
                    'id' => $comment->id,
                    'comment' => $comment->comment,
                ];
            }),
        ];
    }

但是结果将不包含post_id作为键,如何使它返回具有键post_id的注释集合?

更新

use App\models\Post;
use App\Http\Resources\Postas PostResource;

Route::get('/posts', function () {
    return PostResource::collection(Post::all()->keyBy->slug);
});

这可以正常工作,但是如果我将用户资源内的帖子收集用作关系,则它不起作用!这就是我收集评论的要求。

2 个答案:

答案 0 :(得分:1)

我做了什么,我创建了另一个ResourceGroupCollection类

<?php
namespace App\Http\Resources\Collection;

use Illuminate\Http\Resources\Json\ResourceCollection;

class CommentGroupCollection extends ResourceCollection
{
    public $collects = 'App\Http\Resources\Collection\CommentCollection';

    public $preserveKeys = true;

    public function toArray($request)
    {
        return $this->collection;
    }

}

<?php
namespace App\Http\Resources\Collection;

use Illuminate\Http\Resources\Json\ResourceCollection;

class CommentCollection extends ResourceCollection
{
    public $collects = 'App\Http\Resources\Comment';

    public $preserveKeys = true;

    public function toArray($request)
    {
        return $this->collection;
    }

}

and then 

new CommentGroupCollection($comments->groupBy('post_id')),

答案 1 :(得分:0)

就是这样:

     public function toArray($request)
        {
            // return parent::toArray($request);

            return [
                'id' => $this->id,
                'name' => $this->name,
//                'comments' => $this->post->comments->keyBy('post_id')
                'comments' => new CommentCollection($this->post->comments)->keyBy('post_id')

            ];
        }