在 Laravel 资源中使用 groupBy

Mwt*_*eex 3 laravel

我想传递一个groupBy带有 laravel 资源的集合,但问题是当我使用该collection方法时,我无法修改 json 并且会抛出错误:

帖子资源:

public function toArray($request)
{
    return [
        'comments' => CommentResource::collection($this->comments->groupBy('star')),
    ];
}
Run Code Online (Sandbox Code Playgroud)

该集合中不存在属性 [star]

但是,一旦我从集合中删除 groupBy 方法,它就会起作用。那么当资源按特定键分组时,如何获取和修改呢?

Mwt*_*eex 10

“一旦创建了集合,您就可以对其进行分组。”

CommentResource::collection($this->comments)->collection->groupBy('star')
Run Code Online (Sandbox Code Playgroud)

devcircus在 github 上给出了他的答案