Search code examples
symfonydoctrine-ormpagerfanta

Serializing doctrine object with ManyToMany relation


I'm trying to serialize object to json by following symfony official docs. I'v got Pagerfanta object(getting it from repository just like in Demo Application)

    public function findOneIncRel(int $page = 1): Pagerfanta
    {
        $query = $this->createQueryBuilder('b')
            ->select('b, m, a')
            ->leftJoin('b.marks', 'm')
            ->leftJoin('b.authors', 'a')
            ->getQuery();
        return $this->createPaginator($query, $page);
    }

    private function createPaginator(Query $query, int $page): Pagerfanta
    {
        $paginator = new Pagerfanta(new DoctrineORMAdapter($query));
        $paginator->setMaxPerPage(10);
        $paginator->setCurrentPage($page);

        return $paginator;
    }

I need to turn result into JSON.

I'v tried this:

$books = $bookRepository->findAllIncRel(1);
$encoder = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$normalizers[0]->setCircularReferenceLimit(1);
$normalizers[0]->setCircularReferenceHandler(function ($object) {
    return $object->getId();
});
$serializer = new Serializer($normalizers, $encoder);
return new JsonResponse($serializer->serialize($books->getCurrentPageResults(), 'json'));

Structure of instance of Book is like this:

-id: ...
-marks: PersistentCollection ...
-authors: PersistentCollection ...
...

But all I'v got are uncatchable 500 error or "Maximum execution time of 30 seconds exceeded" I don't know what is problem here. Is there some other way to serialize PagerFanta object?

Best regards!


Solution

  • Answer was pretty simple - instead of using Circular Reference Handler I just used $normalizer->setIgnoredAttributes(array(...related fields of 2nd level objects...))