我有一个实体,它有一个指向相同类型的另一个对象的属性,比如标记为现有实体副本的实体的duplicatedFrom。
实体类如下所示:
class Foo
{
private string $id;
private string $name;
private string $content;
private ?Foo duplicatedFrom;
}我希望返回的结果类似于:
{
"@id": "/api/foo/2",
"@type": "Foo",
"name": "bar",
"content": "abce",
"duplicatedFrom": "/api/foo/1"
}但我得到的却是:
{
"@id": "/api/foo/2",
"@type": "Foo",
"name": "bar",
"content": "abce",
"duplicatedFrom": {
"@id": "/api/foo/1",
"@type": "Foo",
"name": "bar",
"content": "abce",
"duplicatedFrom": null
}
}Foo::duplicatedFrom的实体引用是完全序列化的,我希望只使用id值,而不是整个实体。
我一直在尝试序列化配置,将duplicatedFrom的max-depth设置为0或1,但结果是相同的。
适用的序列化程序组:
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping">
<class name="Foo">
<!-- rest of the declaration omitted -->
<!-- tried with max-depth 1 and 0 -->
<attribute name="duplicatedFrom" max-depth="1">
<group>foo_item</group>
<group>foo_collection</group>
</attribute>
</class>
</serializer>api资源配置:
<resources xmlns="https://api-platform.com/schema/metadata">
<resource class="Foo">
<attribute name="normalization_context">
<attribute name="groups">
<attribute>foo_collection</attribute>
</attribute>
</attribute>
</resource>我如何才能做到这一点呢?
发布于 2020-10-25 17:56:00
我不明白为什么这不能用注解来完成。您可以使用所需的group创建另一个getter,而不是将group绑定到确切的属性。
对于您的示例:
/**
* @Groups({"foo"})
*/
private ?Foo duplicatedFrom;你可以这样做:
private ?Foo duplicatedFrom;
/**
* @Groups({"foo"})
*/
public function getDuplicatedFromId(): ?string
{
return $this->getDuplicatedFrom()->getId();
}我知道这不是最好的方法,但它可能会有帮助。
https://stackoverflow.com/questions/61159818
复制相似问题