Symfony - ManyToOne 关系中的循环引用错误

Symfony - Circular reference error in ManyToOne relationships

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

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

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

我收到以下错误:

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

你知道我该如何解决吗?

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

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

向您的 ProductImage 添加 use 语句 class:

use Symfony\Component\Serializer\Annotation\Groups;

向要序列化的属性添加一个组,但跳过产品 属性:

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

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

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

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