Symfony 4 serialize entity wihout relations

前端 未结 3 1809
我寻月下人不归
我寻月下人不归 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 20:55

    ignored_attributes provides a quick, and easy way to accomplish what you're looking for.

    $serializer->serialize($object, 'json', ['ignored_attributes' => ['ignored_property']]); 
    

    Heres how its used with the serializer:

    use Acme\Person;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    use Symfony\Component\Serializer\Serializer;
    
    $person = new Person();
    $person->setName('foo');
    $person->setAge(99);
    
    $normalizer = new ObjectNormalizer();
    $encoder = new JsonEncoder();
    
    $serializer = new Serializer([$normalizer], [$encoder]);
    $serializer->serialize($person, 'json', ['ignored_attributes' => ['age']]); 
    

    Documentation: https://symfony.com/doc/current/components/serializer.html#ignoring-attributes

提交回复
热议问题