【问题标题】:Symfony - Circular reference error in ManyToOne relationshipsSymfony - 多对一关系中的循环引用错误
【发布时间】:2021-05-16 00:19:42
【问题描述】:

我正在使用 Symfony 5 和学说。我有两个具有多对一关系的实体(ProductProductImage)。每个产品可以有多个图像,并且产品实体具有getProductImages() 方法来获取其产品图像。

但是当我在控制器响应中使用这种方法时:

return $this->json($product->getProductImages());

我收到以下错误:

A circular reference has been detected when serializing the object of class "App\Entity\Product"

你知道我该如何解决吗?

【问题讨论】:

  • 你试过使用序列化组吗?

标签: symfony doctrine


【解决方案1】:

$this->json() 使用序列化程序将 ProductImage 转换为 json。当序列化程序尝试序列化 ProductImage 时,它​​会找到对其 Product 的引用并尝试对其进行序列化。然后,当它序列化 Product 时,它会找到对 ProductImage 的引用,这会导致错误。

如果您的 json 中不需要 Product 信息,解决方案是定义一个序列化组并跳过导致错误的 Product 属性的序列化。

在您的 ProductImage 类中添加一个 use 语句:

use Symfony\Component\Serializer\Annotation\Groups;

向要序列化的属性添加组,但跳过 Product 属性:

/**
 * @Groups("main")
 */
private $id;

/**
 * @Groups("main")
 */
private $filename;

并在您的控制器中指定要在$this->json() 中使用的组:

    return $this->json(
        $product->getProductImages(),
        200,
        [],
        [
            'groups' => ['main']
        ]
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多