避免使用 Doctrine 实体和 JMSserializer 进行递归 [英] Avoiding recursion with Doctrine entities and JMSserializer

查看:27
本文介绍了避免使用 Doctrine 实体和 JMSserializer 进行递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Symfony2、Doctrine、FOSRestBundle 和 JMSSerializer 构建 REST API.

I am building a REST API using Symfony2, Doctrine, FOSRestBundle and JMSSerializer.

我遇到的问题是在序列化我的实体时,序列化程序会引入任何相关实体.例如,对于作为故事板一部分的故事的一部分的任务,因此在序列化任务时,我得到的输出包括故事,该故事包括电路板,然后包括电路板上的所有其他故事.

The issue I am having is when serializing my entities, the serializer pulls in any related entities. Eg for a task that is part of a story which is part of a board, so when serializing the task I get output that includes the story which includes the board, which then includes all other stories on the board.

是否有一种简单的方法可以限制这种情况,而只包含foreignIds?

Is there an easy way to limit this, and just include the foreignIds instead?

推荐答案

检查 Serializer/Handler/DoctrineProxyHandler.php 文件.现在,如果你评论这一行:

Check the Serializer/Handler/DoctrineProxyHandler.php file on JMSSerializerBundle. Now, if you comment this line:

public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
    {
        if (($data instanceof Proxy || $data instanceof ORMProxy) && (!$data->__isInitialized__ || get_class($data) === $type)) {
            $handled = true;

            if (!$data->__isInitialized__) {
                //$data->__load();
            }

它将停止延迟加载您的实体.如果这就是您要寻找的内容,那么继续创建您自己的处理程序 你不懒加载的地方.

It will stop lazy loading your entities. If this is what you're looking for, then just go ahead and create your own handler where you don't lazy load.

如果这不正确,我建议您在根据自己的喜好将实体发送到 JMSSerializerBundle 之前自定义实体.例如,在任何相关实体中,我需要 ID,而在其他实体中,我需要自定义列名称,如代码、名称或任何内容.

If this isn't correct, I recommend that you customize your entities before sending them to JMSSerializerBundle at your taste. For example, in any related entities I want the ID, while in others i need a custom column name like code, or name, or anything.

我只是创建了实体对象的副本,然后开始获取关系所需的字段.然后,我对该副本进行序列化.JMSSerializerBundle 不会延迟加载,因为我已经提供了正确的字段.

I just create a copy of my entity object and then start getting the fields I need for relationships. Then, I serialize that copy. JMSSerializerBundle won't lazy load because I already provided the proper fields.

这篇关于避免使用 Doctrine 实体和 JMSserializer 进行递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆