简体   繁体   English

使用ManyToMany关系序列化学说对象

[英]Serializing doctrine object with ManyToMany relation

I'm trying to serialize object to json by following symfony official docs. 我正在尝试通过遵循symfony官方文档将对象序列化为json。 I'v got Pagerfanta object(getting it from repository just like in Demo Application) 我有Pagerfanta对象(就像在演示应用程序中那样从存储库中获取它)

    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. 我需要将结果转换为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: Book实例的结构是这样的:

-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. 但是我所能得到的都是无法捕获的500错误或“超过30秒的最大执行时间”,我不知道这里是什么问题。 Is there some other way to serialize PagerFanta object? 还有其他序列化PagerFanta对象的方法吗?

Best regards! 最好的祝福!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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