如何通过其ID更改ManyToMany的路径

问题描述 投票:1回答:1

我用API平台创建了一个Symfony项目,我想针对ManyToMany关系更改Api平台的默认行为。默认情况下,此返回关系的路径,我希望他返回其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;
}

我目前的杰森

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

所需的杰森

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

对不起我的英语不好

symfony4 api-platform.com
1个回答
2
投票

终于找到了解决方法

需要使用@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
      }
    ]
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.