Symfony 4 serialize entity wihout relations

前端 未结 3 1784
我寻月下人不归
我寻月下人不归 2021-01-05 20:35

I\'ve have to log changes of each entities. I\'ve Listener which listen for doctrine\'s events on preRemove, postUpdate and postDelete. My enity AccessModule has relations:<

3条回答
  •  再見小時候
    2021-01-05 21:14

    Tested in Symfony 4.1, here is the documentation that actually works https://symfony.com/blog/new-in-symfony-2-7-serialization-groups

    Robert's explanation https://stackoverflow.com/a/48756847/579646 is missing the $classMetadataFactory in order to work. Here is my code:

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $encoders = [new JsonEncoder()];
        $normalizer = new ObjectNormalizer($classMetadataFactory);
        $normalizer->setCircularReferenceLimit(2);
        // Add Circular reference handler
        $normalizer->setCircularReferenceHandler(function ($object) {
            return $object->getId();
        });
        $normalizers = [$normalizer];
        $serializer = new Serializer($normalizers, $encoders);
        $jsonContent = $serializer->serialize($jobs, 'json', array('groups' => ['default']));
    
        return JsonResponse::fromJsonString($jsonContent);
    

提交回复
热议问题