1

我正在使用 Api-Platform 为 AngularJs 应用程序构建我的第一个 rest API,

我想在这里获得我所有的项目实体,比如 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
    }

这是 Rest APi 的一个很好的实用性吗?

4

1 回答 1

0

API 平台具有用于在父 JSON 文档中嵌入关系的内置函数。

您的实体将如下所示:

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 } ]

小心,它会嵌入父级以及父级的父级等等。如果要更改此设置,则需要创建自定义规范器。由于有了新的@MaxDepth注解,当 Symfony 3.1 发布时会更加直接。

于 2016-02-01T23:24:37.097 回答