M
M
Maxim Lagoysky2019-12-16 15:15:04
symfony
Maxim Lagoysky, 2019-12-16 15:15:04

Symfony serialize stops working when adding a certain connection, why?

Hello everyone, there are 3 tables, user, ticket, ticket_assigned_user, ticket has a relationship with ticket_assigned_user, this relationship is OneToMany. But if I add a OneToMany connection between user and ticket_assigned_user, then the serializer leaves so that the page crashes with a timeout error. What exactly is the problem here?

How do I serialize

$encoders = [new XmlEncoder(), new JsonEncoder()];
        $classMetadataFactory = new ClassMetadataFactory(new XmlFileLoader('/var/www/new-sys.local/config/packages/serialization/definition.xml'));
        $defaultContext = [
            AbstractObjectNormalizer::MAX_DEPTH_HANDLER => function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
                return $innerObject->id;
            },
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
                return $object->getId();
            },
        ];
        $normalizers = [
            new DateTimeNormalizer(),
            new ObjectNormalizer(
                $classMetadataFactory,
                null,
                null,
                null,
                null,
                null,
                $defaultContext
            ),
        ];
        $serializer = new Serializer($normalizers, $encoders);
        $tickets = $this->em->getRepository(Ticket::class)->findBy([], null, 10);
        $jsonContent = $serializer->serialize($tickets, 'json', [
            AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
        ]);

And maybe someone knows a good example of how an api project works on symfony using symfony/serializator?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Getmansky, 2019-12-18
@lagoy

Since you do not just refer to the first class to the second and the second to the first, but through the third entity, Doctrine does not process them correctly. In such cases, it is worth removing the output of the user.assignedTickets field , just through the array you mentioned

[AbstractNormalizer::ATTRIBUTES => ['assignedUsers' => ['assignedTickets']]
, then the structure will be flat, but without going into recursion.
Only documentation , and then you just need to think through all the requests. If we talk about this task, if I were you, I would just make one method in the ticket repository class and implement an SQL query in it, bypassing Doctrine, since in the end you need to get json, and using ORM gives a lot of overhead and suboptimal batches of queries to DB.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question