使用Api-Platform水合加入实体

时间:2016-02-01 10:41:43

标签: symfony api-platform.com

我正在使用Api-Platform为AngularJs应用构建我的第一个休息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中获取Project对象而不是像这样引用吗?

    {
        "@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的一个很好的实用性吗?

1 个答案:

答案 0 :(得分:0)

API平台具有Complete List of MIME Types的内置功能。<​​/ p>

您的实体将如下所示:

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

小心,它将嵌入父级以及父级的父级,依此类推。如果要更改此设置,则需要创建自定义规范化程序。由于embedding relations in the parent JSON document,Symfony 3.1将会发布,这将更加直截了当。