如何通过 ID 更改 ManyToMany 的路径

How to change the path of ManyToMany by its ID

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

我阅读了 API-平台文档,但没有找到任何内容

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

对不起我的英语不好


终于找到解决方法

需要对 select 特定字段使用 @groups

Link to the documentation

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