分形中的JsonApiSerializer包含的数据类型为null

时间:2018-11-21 16:26:23

标签: laravel thephpleague-fractal

这是我目前在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');

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

1 个答案:

答案 0 :(得分:0)

对于可能偶然发现此问题的人。我想念的是,您需要在相应的转换器中设置ressourceKey,在其中您调用collection()以包括数据。当然有道理。就我而言:

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');
}