问题描述
我有一个简单的实体类:
I have a simple entity class:
<?php
namespace AppBundleEntity;
use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;
/**
* @ORMEntity(repositoryClass="CompanyUserRepository")
* @ORMTable(name="company_users")
*/
class CompanyUser
{
/**
* @ORMColumn(type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMColumn(type="string", length=100)
*/
private $firstName;
/**
* @ORMColumn(type="string", length=100)
*/
private $lastName ;
/**
* @ORMOneToMany(targetEntity="Score", mappedBy="user")
*/
private $scores;
/**
* Constructor
*/
public function __construct()
{
$this->scores = new ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* @param string $firstName
*
* @return CompanyUser
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* @param string $lastName
*
* @return CompanyUser
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Add score
*
* @param AppBundleEntityScore $score
*
* @return CompanyUser
*/
public function addScore(AppBundleEntityScore $score)
{
$this->scores[] = $score;
return $this;
}
/**
* Remove score
*
* @param AppBundleEntityScore $score
*/
public function removeScore(AppBundleEntityScore $score)
{
$this->scores->removeElement($score);
}
/**
* Get scores
*
* @return DoctrineCommonCollectionsCollection
*/
public function getScores()
{
return $this->scores;
}
}
当我尝试获取所有用户并将它们序列化为 json 时,问题就来了:
The problem comes when I try to get all users and serialize them in json:
/**
* @Route("/api/getUsers", name="getUsers")
*/
public function getUsers(Request $request){
$users = $this->getDoctrine()
->getRepository('AppBundle:CompanyUser')
->findAll();
$serializer = $this->get('serializer');
$data = $serializer->serialize($users, 'json');
return new Response($users);
}
我得到检测到循环引用(配置限制:1).当我删除 getScores 吸气剂时,一切正常.我只需要获取 id、firstName 和 lastName.有没有办法不序列化其他对象?
I get A circular reference has been detected (configured limit: 1).When I remove the getScores getter everything works fine. I need to get only the id, firstName and lastName. Is there a way to not serialize the other objects?
推荐答案
嗯,用 循环引用 序列化具有关系的实体时.
Well, it is a common thing to handle with circular references when serializing entities with relations.
解决方案编号1:实现可序列化接口并使关系属性不序列化/反序列化(大多数情况下,这是一个有效的解决方案)
Solution no. 1: Implements serializable interface and make relations attributes are not serialize/unserialize (most cases, it is a valid solution)
解决方案编号2:此规范器的 setCircularReferenceLimit()
方法设置在将同一对象视为循环引用之前将其序列化的次数.它的默认值为 1.因此,在调用 serialize()
方法之前,请执行以下操作:
Solution no. 2: The setCircularReferenceLimit()
method of this normalizer sets the number of times it will serialize the same object before considering it a circular reference. Its default value is 1. So, before calling serialize()
method, do this:
public function getUsers(Request $request){
$users = $this->getDoctrine()
->getRepository('AppBundle:CompanyUser')
->findAll();
$serializer = $this->get('serializer');
$serializer->setCircularReferenceLimit(2); // Change this with a proper value for your case
$data = $serializer->serialize($users, 'json');
return new Response($data);
}
**** 更新 ****
**** UPDATE ****
正如@Derek 在他的评论中所说,解决方案没有.2 在某些 Symfony 版本中可能无效.然后您可以尝试通过这种方式为循环引用设置处理程序:
As @Derek says in his comment, solution no. 2 can be invalid in some versions of Symfony. Then you can try to set a handler for circular references this way:
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getName(); // Change this to a valid method of your object
});
$serializer = new Serializer(array($normalizer), array($encoder));
var_dump($serializer->serialize($org, 'json'));
这应该返回您的实体值而不是迭代关系.
This should return your entity value instead to iterate over relations.
这篇关于Symfony 序列化学说实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!