Search code examples
symfonydoctrine

Symfony - Circular reference error in ManyToOne relationships


I am using Symfony 5 and doctrine. I have two entities with ManyToOne relationships (Product and ProductImage). Each product can have multiple images and the product entity has getProductImages() method to fetch its product images.

But when I use this method in controller response like this:

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

I get the following error:

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

Do you have any idea how can I solve it?


Solution

  • $this->json() uses a serializer to convert the ProductImage into json. When the serializer tries to serialize the ProductImage it finds the reference to its Product and tries to serialize that too. Then when it serializes the Product it finds the reference back to the ProductImage, which causes the error.

    If you do not need the Product information in your json, the solution is to define a serialization group and skip the serialization of the Product property that is causing the error.

    Add a use statement to your ProductImage class:

    use Symfony\Component\Serializer\Annotation\Groups;

    Add a group to the properties you want to serialize, but skip the Product property:

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

    And in your controller specify the group to use in $this->json():

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