【问题标题】:Only return specific fields for specific groups when serializing with Symfony 4使用 Symfony 4 序列化时仅返回特定组的特定字段
【发布时间】:2019-04-11 09:25:47
【问题描述】:

Symfony 4. 我有两个实体,CatOwner

class Cat
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups("cats")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("cats")
     */
    private $name;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Owner", mappedBy="cat")
     * @Groups("cats")
     */
    private $owners;
}

class Owner
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups("cats")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("owners")
     */
    private $name;
}

我的 API 端点需要返回 2 个密钥,owners(所有所有者的列表)和 cats(所有猫及其所有者的列表)。

public function index()
{
    $repository = $this->getDoctrine()->getRepository(Owner::class);
    $owners = $repository->findAll();
    $repository = $this->getDoctrine()->getRepository(Cat::class);
    $cats = $repository->findAll();
    return $this->json([
        'owners' => $owners,
        'cats' => $cats,
    ], 200, [], ['groups' => ['owners', 'cats']]);
}

这可行,但有 1 个问题:cats 列表包含每个所有者的完整所有者信息,即:

{
  "owners": [
    {
      "id": 1,
      "name": "John Smith"
    }
  ],
  "cats": [
    {
      "id": 1,
      "name": "Miaow",
      "owners": [ 
        {
          "id": 1,
          "name": "John Smith"
        }
      ]
    }
  ]
}

我想要的是cat 对象中的owners 键只返回所有者的id,如下所示:

{
  "owners": [
    {
      "id": 1,
      "name": "John Smith"
    }
  ],
  "cats": [
    {
      "id": 1,
      "name": "Miaow",
      "owners": [ 
        1
      ]
    }
  ]
}

【问题讨论】:

    标签: php symfony serialization


    【解决方案1】:

    您可以将 getter 用于特定组并具有特定的序列化名称。

    Cat:

    /**
     * @Groups("cats")
     * @SerializedName("owners")
    */
    public function getOwnersIds(): iterable
    {
        return $this->getOwners()->map(function ($owner) {
            return $owner->getId();
        })->getValues();
    }
    

    【讨论】:

    • 谢谢。由于$this->getOwners() 返回的是一个集合,而不是一个数组,所以它不太有效。但是你给我指出了正确的方向。这有效:return $this->getOwners()->map(function ($owner) { return $owner->getId(); })->getValues();。如果你更新你的答案,我会把它标记为正确的。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2020-01-05
      • 2015-01-27
      相关资源
      最近更新 更多