首页 > 解决方案 > 如何通过 ID 更改 ManyToMany 的路径

问题描述

我使用 API-Platform 创建了一个 Symfony 项目,我想更改 Api 平台的默认行为,以实现多对多关系。默认情况下,这个返回关系路径,我希望他返回他的 ID

我阅读了 API-Platform 文档,但没有找到任何东西

use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ApiResource(attributes={
 *     "normalization_context"={"groups"={"read"}}
 * })
 */

class Work
{
    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("read")
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\WorkFilter", inversedBy="works")
     * @Groups("read")
     */
    private $filters;
}

我现在的 Json

[
  {
    "title": "Work 1",
    "filters": [
      "/api/work_filters/1",
      "/api/work_filters/2"
    ]
  }
]

所需的 Json

[
  {
    "title": "Work 1",
    "filters": [
      "1",
      "2"
    ]
  }
]

对不起我的英语不好

标签: symfony4api-platform.com

解决方案



最后我找到了解决方案

需要@groups用于选择特定字段

链接到文档

use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ApiResource(attributes={
 *     "normalization_context"={"groups"={"work"}}
 * })
 */

class Work
{
    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("work")
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\WorkFilter", inversedBy="works")
     * @Groups("work")
     */
    private $filters;
}
use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ApiResource(attributes={
 *     "normalization_context"={"groups"={"work"}}
 * })
 */

class WorkFilter
{
    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("work")
     */
    private $id;
}
[
  {
    "title": "Work 1",
    "filters": [
      {
        "id": 1
      },
      {
        "id": 2
      }
    ]
  }
]

推荐阅读