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

问题描述

我有两个实体:Tag、Post。 关于多对多

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

我想通过标签返回与标签相关联的帖子。 但我也想返回与标签返回的帖子对象关联的标签

这会产生一个错误

“加入的关系总数已超过指定的最大值。如有必要,使用“api_platform.eager_loading.max_joins”配置键(https://api-platform.com/docs/core/performance/#eager-loading)提高限制,或使用“enable_max_depth”限制最大序列化深度" Symfony 序列化程序 (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:collection:Tag'])]
private $name;

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

Post 实体中的标签字段:

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

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

解决方法

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

就您而言,我认为您需要从 read:item:Tag 实体的​​ $tags 属性中删除 Post 组。

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

我意识到这可能会影响从 posts 端点检索数据的方式,但似乎对于关系来说是必要的,以避免递归。组基础架构可能会令人困惑。