PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 16, 2022

[FIXED] Symfony - Circular reference error in ManyToOne relationships

 January 16, 2022     doctrine, symfony     No comments   

Issue

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']
        ]
    );


Answered By - Marleen
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing