【问题标题】:Type of included data is null with JsonApiSerializer in FractalFractal 中的 JsonApiSerializer 包含的数据类型为空
【发布时间】:2018-11-22 16:16:01
【问题描述】:

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

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

【问题讨论】:

    标签: laravel thephpleague-fractal


    【解决方案1】:

    对于可能偶然发现这一点的人。我错过了您需要在调用 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');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多