首页 > 解决方案 > Fractal 中的 JsonApiSerializer 包含的数据类型为空

问题描述

这就是我目前在 Laravel 中使用 Fractal 的 Fractal 的 JsonApiSerializer 得到的:

{
        "type": "projects",
        "id": "18",
        "attributes": {
            "name": "pariatur",
            "parent_id": 1
        },
        "relationships": {
            "tasks": {
                "data": [
                    {
                        "type": null,
                        "id": "245"
                    }
                ]
            }
        }
    }
],
"included": [
    {
        "type": null,
        "id": "435",
        "attributes": {
            "name": "incidunt",
            "content": "Laboriosam occaecati qui voluptas suscipit. Magni numquam incidunt pariatur et at. Alias molestias perspiciatis quae sit.",
            "project_id": 12,
            "due_at": "1971-05-19"
        }
    },

我知道您可以像这样设置请求资源的类型:

// Important, notice the Resource Key in the third parameter:
$resource = new Item($book, new JsonApiBookTransformer(), 'books');
$resource = new Collection($books, new JsonApiBookTransformer(), 'books');

如何对包含的数据执行此操作?

标签: laravelthephpleague-fractal

解决方案


对于可能偶然发现这一点的人。我错过了您需要在调用 collection() 以包含数据的相应转换器中设置 ressourceKey。当然有道理。就我而言:

public function includeTasks(Project $project, ParamBag $paramBag)
{
    list($orderCol, $orderBy) = $paramBag->get('order') ?: ['created_at', 'desc'];

    $tasks = $project->tasks()->orderBy($orderCol, $orderBy)->get();

    return $this->collection($tasks, App::make(TaskTransformer::class), 'tasks');
}

推荐阅读