Home > Blockchain >  Symfony Serializer circular reference due to many-to-many relationship
Symfony Serializer circular reference due to many-to-many relationship

Time:03-27

i require an api that retruns a json data so i'm trying to send json data via a controller in symfony and I'm using serializer but I'm having issues assigning groups to the attributes with the many to many relationships(category and users). Controller Code :

        $serializer = $this->container->get('serializer');
        $JSONprojects = $serializer->serialize($DATA, 'json', ['groups' => ['project','category']]);
        return new Response($JSONprojects); 

        return $JSONprojects ;

project.php (enity).

class Project
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @Groups("project")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("project")
     */
    private $name;


/**
 *
 * @ORM\ManyToMany(targetEntity=User::class, mappedBy="projects")
 */
private $users;

/**
 * @Groups("project")
 * @ORM\ManyToOne(targetEntity=User::class, inversedBy="myproject")
 * @ORM\JoinColumn(nullable=false)
 */
private $creator;

/**
 *
 * @ORM\ManyToOne(targetEntity=Category::class, inversedBy="projects")
 */
private $category;

Category.php (entity)

 class Category
 {
/**
 * @ORM\Id
 * @ORM\GeneratedValue
 * @ORM\Column(type="integer")
 *
 */
private $id;

/**
 * 
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 *  
 * @ORM\Column(type="text")
 */
private $image;

/**
 *  
 * @ORM\OneToMany(targetEntity=Project::class, mappedBy="category")
 */
private $projects;

CodePudding user response:

You can handle circular references with the serializer like this:

$JSONprojects = $serializer->serialize($data, 'json', [
    'circular_reference_handler' => function ($object) { return $object; },
    'groups' => ['project','category']
]);

More on circular references in the Symfony docs.

CodePudding user response:

Do not serialize doctrine entity objects, use Data Transfer Object.

DTO will save the headache, although much more code to write.

  • Related