我遇到了与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);
}
最佳答案 你需要调用$normalizer-> setCircularReferenceHandler()
请阅读以下官方文档: