在Symfony中检测到循环引用

时间:2016-08-09 09:52:31

标签: php symfony circular-reference serializer

我遇到与Symfony中的循环引用相关的问题,我怀疑是 由序列化器引起但我还没有找到任何答案。以下是我创建的实体,路线和控制器。任何有关这方面的建议都将不胜感激。

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();
    }
   //...
   //...
}

Dieta.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("dietas/list/user/{id}", name="userDietas")
 */

DietaController.php的方法

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);
    }

2 个答案:

答案 0 :(得分:1)

您需要致电$normalizer->setCircularReferenceHandler() 请阅读以下官方文档:

handling-circular-references

答案 1 :(得分:0)

 $jsonContent = $serializer->serialize($yourObject, 'json', [
       'circular_reference_handler' => function ($object) {
           return $object->getId();
        }
    ]);

为我工作。希望这会有所帮助(Symfony> = 4.2)