我正在使用Symfony 5和教义。我有两个具有ManyToOne关系的实体(Product和ProductImage)。每个产品可以有多个图像,并且产品实体有getProductImages()方法来获取其产品图像。
但是当我在控制器响应中使用此方法时,如下所示:
return $this->json($product->getProductImages());我得到以下错误:
A circular reference has been detected when serializing the object of class "App\Entity\Product"你知道我该怎么解决吗?
发布于 2021-05-15 16:14:10
$this->json()使用序列化程序将ProductImage转换为json。当序列化程序试图序列化ProductImage时,它会找到对其产品的引用,并尝试序列化该引用。然后,当它序列化产品时,它会找到对ProductImage的引用,这会导致错误。
如果不需要json中的产品信息,则解决方案是定义序列化组并跳过导致错误的property的序列化。
向ProductImage类添加一个use语句:
use Symfony\Component\Serializer\Annotation\Groups;
将组添加到要序列化的属性,但跳过property:
/**
* @Groups("main")
*/
private $id;
/**
* @Groups("main")
*/
private $filename;在控制器中指定要在$this->json()中使用的组
return $this->json(
$product->getProductImages(),
200,
[],
[
'groups' => ['main']
]
);https://stackoverflow.com/questions/67545029
复制相似问题