使用symfony在apiplatform上调用两次关系问题

问题描述 投票:0回答:2

我有两个实体:标签、帖子。 关于多对多

我在 GET 中有一个 API 路由:/api/tags/{id}

我想通过标签返回与该标签关联的帖子。 但我还想返回与 Tag 返回的 posts 对象关联的标签。

这会产生错误:

“连接关系的总数已超过指定的最大值。如有必要,请使用“api_platform.eager_loading.max_joins”配置键提高限制(https://api-platform.com/docs/core/performance/#eager -loading),或使用 Symfony 序列化器的“enable_max_depth”选项限制最大序列化深度(https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth)。

标签实体:

#[ApiResource(
normalizationContext: ['groups' => ['read:collection:Tag']],
collectionOperations:['get'],
paginationEnabled: false,
itemOperations: [
    'get' => [
        'normalization_context' => ['groups' => [
            'read:item:Tag',
            'read:collection:Tag'
            ]]
        ],
]
)]

class Tag
{
/**
 * @ORM\Id
 * @ORM\GeneratedValue
 * @ORM\Column(type="integer")
 */
#[Groups(['read:collection:Post', 'read:item:Category', 'read:collection:Tag'])]
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
#[Groups(['read:collection:Post', 'read:item:Category', 'read:collection:Tag'])]
private $name;

/**
 * @ORM\ManyToMany(targetEntity=Post::class, mappedBy="tags")
 */
#[Groups(['read:item:Tag'])]
private $posts;

Post 实体中的 tag 字段:

/**
 * @ORM\ManyToMany(targetEntity=Tag::class, inversedBy="posts")
 */
#[Groups(['read:collection:Post', 'read:item:Category','read:item:Tag'])]
private $tags;

我尝试使用错误消息中所示的“enable_max_depth”选项来限制最大序列化深度,但它不起作用。

api symfony api-platform.com
2个回答
4
投票

当同一序列化组用于实体的关系属性以及从关联实体返回的属性时,我在多对多关系中遇到了这个问题。

就您而言,我认为您需要从

read:item:Tag
实体的
$tags
属性中删除
Post
组。

/**
 * @ORM\ManyToMany(targetEntity=Tag::class, inversedBy="posts")
 */
#[Groups(['read:collection:Post', 'read:item:Category'])]
private $tags;

我意识到这可能会影响从

posts
端点检索数据的方式,但这对于关系来说似乎是必要的,以避免递归。团体基础设施可能会变得混乱。


0
投票

只需使用:#[ApiResource(forceEager: false)]

© www.soinside.com 2019 - 2024. All rights reserved.