繁体   English   中英

序列化类“App\Entity\Catalog”的对象时检测到循环引用(配置限制:1)

[英]A circular reference has been detected when serializing the object of class "App\Entity\Catalog" (configured limit: 1)

这是我的 2 个实体

<?php

namespace App\Entity;

use App\Repository\CatalogRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CatalogRepository::class)
 */
class Catalog
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity=Title::class, mappedBy="Catalog", orphanRemoval=true)
     */
    private $titles;

    public function __construct()
    {
        $this->titles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return Collection<int, Title>
     */
    public function getTitles(): Collection
    {
        return $this->titles;
    }

    public function addTitle(Title $title): self
    {
        if (!$this->titles->contains($title)) {
            $this->titles[] = $title;
            $title->setCatalog($this);
        }

        return $this;
    }

    public function removeTitle(Title $title): self
    {
        if ($this->titles->removeElement($title)) {
            // set the owning side to null (unless already changed)
            if ($title->getCatalog() === $this) {
                $title->setCatalog(null);
            }
        }

        return $this;
    }
}

<?php

namespace App\Entity;

use App\Repository\TitleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=TitleRepository::class)
 */
class Title
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $year;

    /**
     * @ORM\Column(type="float", nullable=true)
     */
    private $rating;

    /**
     * @ORM\ManyToOne(targetEntity=Catalog::class, inversedBy="titles")
     * @ORM\JoinColumn(nullable=false)
     */
    private $Catalog;

    public function __construct()
    {
        $this->Catalog = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getYear(): ?int
    {
        return $this->year;
    }

    public function setYear(?int $year): self
    {
        $this->year = $year;

        return $this;
    }

    public function getRating(): ?float
    {
        return $this->rating;
    }

    public function setRating(?float $rating): self
    {
        $this->rating = $rating;

        return $this;
    }

    public function getCatalog(): ?Catalog
    {
        return $this->Catalog;
    }

    public function setCatalog(?Catalog $Catalog): self
    {
        $this->Catalog = $Catalog;

        return $this;
    }
}

当我尝试将它连载时

$em = $doctrine->getManager();
$catalogs = $em->getRepository(Catalog::class)->findAll();
       
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
JsonEncoder()));

$json = $serializer->serialize($catalogs, 'json', ['groups' => ['title','catalog']]);

我收到这个错误

A circular reference has been detected when serializing the object of class "App\Entity\Catalog" (configured limit: 1).

有什么办法可以避免这个问题吗??我知道 catalor 引用了 title 和 totle recerences 目录,但我认为它是建立关系的正确方法,但它不适用于序列化,我应该在关系中更改什么或者我可以序列化它用另一种方式

更新:我尝试了忽略和组,但我得到了同样的错误

在目录

/**
     * @ORM\Column(type="float")
     * @Groups({"group1"})
     */
    private $rating;

    /**
     * @ORM\ManyToOne(targetEntity=Catalog::class, inversedBy="titles")
     * @ORM\JoinColumn(nullable=false)
     * @Ignore()
     */
    private $Catalog;

 $json = $serializer->serialize($catalogs, 'json',  ['groups' => 'group1']);

兄弟问题here 序列化类“App\Entity\User”的对象时检测到循环引用(配置限制:1)

您可以使用官方文档中描述的组概念

您还可以创建一个循环引用处理程序来处理它。 例如,在您的控制器中,您可以序列化 Catalog 实体,如:

<?php

namespace App\Controller;

use App\Repository\CatalogRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

class MainController extends AbstractController
{
    #[Route('/', name: 'app_main')]
    public function index(CatalogRepository $catalogRepository, SerializerInterface $serializer): JsonResponse
    {
        $catalogs = $catalogRepository->findAll();

        $circularRefHandler = fn($catalog, $format, $context)=> $catalog->getName();

        $context = [
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => $circularRefHandler
        ];

        $catalogsJson = $serializer->serialize($catalogs, 'json', $context);


        return $this->json([
            'catalogs' => $catalogsJson
        ]);
    }
}


如果你想使用GetSetMethodNormalizer创建一个上下文GetSetMethodNormalizerContextBuilder

        $circularRefHandler = fn($catalog, $format, $context)=> $catalog->getName();

        $context = [
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => $circularRefHandler
        ];
       $contextBuilder = (new GetSetMethodNormalizerContextBuilder())
            ->withContext($context);

        $catalogsJson = $serializer->serialize($catalogs, 'json',$contextBuilder->toArray());

这个例子的完整代码在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM