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

前端 未结 2 903
夕颜
夕颜 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:13

    In my case I've fixed injecting the serializer service instead of creating a new Serializer instance in the controller method.

    use Symfony\Component\Serializer\SerializerInterface;
    
    //...
    public function createOrder(Request $request, SerializerInterface $serializer)
    {
        //...
        $json = $serializer->serialize($order, 'json', ['groups' => ['normal']]);
        //...
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题