我必须序列化一个对象,我得到了如此常见的“循环引用错误”
我使用了旧的 Symfony 方法:
$normalizer = new ObjectNormalizer();
// Add Circular reference handler
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$normalizers = array($normalizer);
$encoders = [new JsonEncoder()];
$serializer = new Serializer($normalizers, $encoders);
Run Code Online (Sandbox Code Playgroud)
这项工作但从 Symfony 4.2 开始,我得到了您在此问题标题中看到的异常:
使用上下文的“circular_reference_handler”键代替 Symfony 4.2
我在有关序列化程序的 Symfony 文档中找不到对此的任何参考。
https://symfony.com/doc/current/components/serializer.html#handling-circular-references
有谁知道如何使用这个“上下文键”而不是旧方法?
我的 Symfony 4.2.6 应用程序中有一个 ManyToMany 关系,我希望它可以为空。
所以我的第一个实体 SpecialOffers 如下:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SpecialOfferRepository")
*/
class SpecialOffer
{
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Neighbourhood", inversedBy="specialOffers")
*/
private $neighbourhood;
public function __construct()
{
$this->neighbourhood = new ArrayCollection();
}
/**
* @return Collection|Neighbourhood[]
*/
public function getNeighbourhood(): Collection
{
return $this->neighbourhood;
}
public function addNeighbourhood(Neighbourhood $neighbourhood): self
{
if (!$this->neighbourhood->contains($neighbourhood)) {
$this->neighbourhood[] = $neighbourhood;
}
return $this;
}
public function removeNeighbourhood(Neighbourhood $neighbourhood): self
{
if ($this->neighbourhood->contains($neighbourhood)) {
$this->neighbourhood->removeElement($neighbourhood);
} …Run Code Online (Sandbox Code Playgroud)