简体   繁体   中英

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!

答案非常简单-我没有使用循环引用处理程序,而是使用$normalizer->setIgnoredAttributes(array(...related fields of 2nd level objects...))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM