我有一個簡單的實體類:Symfony的序列化主義實體
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="CompanyUserRepository")
* @ORM\Table(name="company_users")
*/
class CompanyUser
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $firstName;
/**
* @ORM\Column(type="string", length=100)
*/
private $lastName ;
/**
* @ORM\OneToMany(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 \AppBundle\Entity\Score $score
*
* @return CompanyUser
*/
public function addScore(\AppBundle\Entity\Score $score)
{
$this->scores[] = $score;
return $this;
}
/**
* Remove score
*
* @param \AppBundle\Entity\Score $score
*/
public function removeScore(\AppBundle\Entity\Score $score)
{
$this->scores->removeElement($score);
}
/**
* Get scores
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getScores()
{
return $this->scores;
}
}
問題是當我試圖讓所有的用戶和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 getter時,一切正常。我只需要獲得id,firstName和lastName。有沒有辦法不序列化其他對象?
對可能序列化的對象實現\ Serializable接口是一種很好的做法。考慮到這一點。 – Muriano