A circular reference has been detected when serializing the object of class “App\Entity\User” (configured limit: 1)

前端 未结 2 904
夕颜
夕颜 2021-01-19 07:25

I am faced with a problem that gives me this error:

A circular reference has been detected when serializing the object of class "App\\Entity\\User&q

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 08:16

    Try to avoid circular reference by using Serialization Groups (work for both Symfony Serializer and jms Serializer). Example when your serialize "User" don't serialize "users" from other entity.

    User

    class User 
    {
    
    /**
     * @Groups("user")
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
    
    /**
     * @Groups("user")
     * @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="users")
     * @ORM\JoinColumn(nullable=false)
     */
    private $entreprise;
    }
    

    Entreprise

    class Entreprise
    {
    /**
     * @Groups("entreprise")
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
    
    
    /**
     * @Groups("user_detail")
     * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="entreprise", orphanRemoval=true)
     */
    private $users;
    

    And then

    $json = $serializer->serialize(
        $user,
        'json', ['groups' => ['user','entreprise' /* if you add "user_detail" here you get circular reference */]
    );
    

    However you have two more option either use Handling Circular References or use Handling Serialization Depth

提交回复
热议问题