【问题标题】:Problem of relation called twice on apiplatform with symfony使用 symfony 在 apiplatform 上调用两次的关系问题
【发布时间】:2021-07-07 12:35:18
【问题描述】:

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

我在 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:item:Category', '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:Category','read:item:Tag'])]
private $tags;

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

【问题讨论】:

  • 错误里面的第二个链接有解决办法。设置#[MaxDepth(1)],错误应该消失了。

标签: api symfony api-platform.com


【解决方案1】:

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

在您的情况下,我认为您需要从 $tags 实体的 $tags 属性中删除 read:item:Tag 组。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多