Symfony found circular link

I ran into a symfony circular link issue that I suspect caused by a serializer, but I haven't found the answers yet. Here are the entities I created, route and controller. Any suggestions in this regard would be greatly appreciated.

User.php

class User
{
    /**
      * @var int
      *
      * @ORM\Column(name="id", type="integer")
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;

    /**
      * @ORM\OneToMany(targetEntity="Dieta", mappedBy="user")
    */
    private $dietas;
    public function __construct()
    {
       $this->dietas = new ArrayCollection();
    }
   //...
   //...
}

Diet.php

    class Dieta
        {
            /**
             * @var int
             *
             * @ORM\Column(name="id", type="integer")
             * @ORM\Id
             * @ORM\GeneratedValue(strategy="AUTO")
             */
            private $id;

            /**
             * @ORM\ManyToOne(targetEntity="User", inversedBy="dietas")
             * @ORM\JoinColumn(name="users_id", referencedColumnName="id")
             */
            private $user;
            public function __construct()
            {
                $this->user = new ArrayCollection();
            }

            //...
            //... 
        }

Route

/**
 * @Route("dietas/list/user/{id}", name="userDietas")
 */

DietaController.php Method

public function userListAction($id)
    {
        $encoders = array(new XmlEncoder(), new JsonEncoder());
        $normalizers = array(new ObjectNormalizer());
        $serializer = new Serializer($normalizers, $encoders);

        $user = $this->getDoctrine()
            ->getRepository('AppBundle:User')->find($id);

        $dietaDatas = $user->getDietas();


        if(!$dietaDatas) {
            throw $this->createNotFoundException(
                'There is no data...'
            );
        }

        $jsonContent = $serializer->serialize($dietaDatas, 'json');
        return new Response($jsonContent);
    }
+4
source share
1 answer

If you need to call $normalizer->setCircularReferenceHandler() , please read the official documentation below:

handling-circular-references

+1
source

Source: https://habr.com/ru/post/1650643/


All Articles