Symfony 5 API 填充相关对象实体

Symfony 5 API populate related object entities

我正在尝试使用 Symfony 5 创建一个简单的网络应用程序。我正在使用 API

目前调用某些端点时它只显示 IRI link 到相关的 link:

我需要显示相关的实体对象本身;如果我得到 Item 端点,相关实体 Program 应该 returned 为:

{
    "id": 1,
    "program": {
        "id": 1,
        "name": "First program"
    },
    "description": "fgdfg",
    "comment": "dfgdfg"
{

所以,这就是 table 的样子:

我认为 setting up a subresource 足以获取对象,但事实并非如此:

  1. InventoryItem实体配置@ApiSubresource注解Program属性:

    /**
     * @ORM\ManyToOne(targetEntity=Program::class, inversedBy="inventoryItems")
     * @ORM\JoinColumn(nullable=false)
     * @ApiSubresource
     */
    private $program;
    
  2. resources.yaml 文件中我配置了子资源:

    App\Entity\InventoryItem:
       properties:
           program:
               subresource:
                   resourceClass: 'App\Entity\Program'
                   collection: true
    

这仍然是 returnIRI 而不是对象,唯一改变的是现在我可以访问此 URL 中当前对象的相关实体:http://localhost:8000/api/inventory_items/1/program.json.

知道如何 return 相关实体对象本身而不是 IRI URL 吗?

您正在搜索以序列化您的项目。所以我猜这更像是一个序列化问题而不是子资源问题。 我认为你应该使用 serialization group 而不是 SubResource.

SOLUTION1 序列化嵌入关系

"Embedding relation" 提供了书籍和作者的示例。

<?php
// api/src/Entity/Item.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource(normalizationContext={"groups"={"item"}})
 */
class Item
{
    /**
     * @Groups({"item"})
     */
    public $description;

    /**
     * @Groups({"item"})
     */
    public $comment;

    /**
     * @Groups({"item"})
     */
    public $program;

    // ...
}

// api/src/Entity/Person.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ApiResource
 */
class Person
{
    /**
     * ...
     * @Groups("item") <=== This is item, not program but you can have two groups
     */
    public $name;

    // ...
}

SOLUTION2 混合子资源和序列化组

这个例子应该可行,但是(如果需要子资源)你也可以混合使用 subresources and serializations,但在你的情况下,我想第一个解决方案是最好的。