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

问题描述

我正在使用Symfony2,Doctrine,FOSRestBundle和JMSSerializer构建一个REST API。



我遇到的问题是序列化我的实体时,序列化器拉入任何相关实体。例如,作为一个董事会成员的故事的一部分的任务,所以当序列化任务时,我得到的输出包括包含董事会的故事,然后包括董事会中的所有其他故事。



有没有一个简单的方法来限制这个,只是包括foreignIds?

解决方案

检查文件在JMSSerializerBundle上。现在,如果你对这一行发表评论:

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

if(!$ data-> __ isInitialized__){
// $ data-> __ load();
}

它将停止延迟加载您的实体。如果这是您正在寻找的,那么请继续执行你不会懒惰的负载。



如果这是不正确的,我建议您自定义您的实体,然后将其发送到JMSSerializerBundle您的口味。例如,在任何相关实体中,我想要ID,而在其他实体中,我需要一个自定义列名称,如代码,名称或任何东西。



我只是创建一个我的实体对象的副本,然后开始获取我需要关系的字段。然后,我序列化该副本。 JMSSerializerBundle不会因为已经提供了正确的字段而加载负载。


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.

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

解决方案

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.

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.

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递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 01:29