Hydrate 使用 Api-Platform 加入实体

Hydrate joined Entities with Api-Platform

我正在使用 Api-平台构建我的第一个 API AngularJs 应用程序,

我想在这里获取我所有的项目实体,例如 juste(与我的 url /projects):

{
  "@context": "/contexts/Project",
  "@id": "/projects",
  "@type": "hydra:PagedCollection",
  "hydra:totalItems": 19,
  "hydra:itemsPerPage": 30,
  "hydra:firstPage": "/projects",
  "hydra:lastPage": "/projects",
  "hydra:member": [
    {
      "@id": "/projects/1",
      "@type": "Project",
      "name": "test1",
      "parent": null,
      "createdAt": "2014-12-22T11:38:13+01:00",
      "updatedAt": null,
      "deletedAt": null
    },
    {
      "@id": "/projects/2",
      "@type": "Project",
      "name": "test2",
      "parent": null,
      "createdAt": "2014-12-22T17:02:50+01:00",
      "updatedAt": null,
      "deletedAt": null
    },
    {
      "@id": "/projects/3",
      "@type": "Project",
      "name": "test3",
      "parent": "/projects/2",
      "createdAt": "2014-12-22T18:28:50+01:00",
      "updatedAt": null,
      "deletedAt": null
    }
  ]
}

但是你可以看到我的项目可以有父项目,所以我得到了我的父项目的引用(像这样 /projects/2 )

我可以直接在 Json 中获取项目对象而不是像这样引用吗?

    {
        "@id": "/projects/3",
        "@type": "Project",
        "name": "test3",
        "parent": {
            "@id": "/projects/2",
            "@type": "Project",
            "name": "test2",
            "parent": null,
            "createdAt": "2014-12-22T17:02:50+01:00",
            "updatedAt": null,
            "deletedAt": null
        },
        "createdAt": "2014-12-22T18:28:50+01:00",
        "updatedAt": null,
        "deletedAt": null
    }

这是一个很好的休息实践 APi ?

API 平台具有 embedding relations in the parent JSON document 的内置功能。

您的实体将如下所示:

namespace AppBundle\Entity;

use Symfony\Component\Serializer\Annotation\Groups;

class Project
{
   private $id;

   /** @Groups({"embed"}) */
   private $parent;

   /** @Groups({"embed"}) */
   private $name;

   /** @Groups({"embed"}) */
   private $createdAt;

   // ...
}

以及服务定义:

# app/config/services.yml
services:
    # ...

    resource.offer:
        parent:    api.resource
        arguments: [ 'AppBundle\Entity\Offer' ]
        calls:
            -      method:    initNormalizationContext
                   arguments: [ { groups: [ embed ] } ]
        tags:      [ { name: api.resource } ]

小心,它会嵌入父级以及父级的父级等等。如果你想改变这个,你需要创建一个自定义规范化器。由于 the new @MaxDepth annotation.

,当 Symfony 3.1 发布时会更加直接