json 使用 Zend Framework 2 将 Doctrine 2 实体持久集合转换为数组的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22107363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:10:12  来源:igfitidea点击:

Best way to convert Doctrine 2 entity persistent collection to array with Zend Framework 2

jsondoctrine-ormframeworkszend-framework2entity

提问by ?ukasz

What is best way (easy) to convert Doctrine 2 entity persistent collection to array with Zend Framework 2? I want convert to array and later output it with JsonView. I can write function which use get_object_var but it is a problem when entity has next entity collection.

使用 Zend Framework 2 将 Doctrine 2 实体持久集合转换为数组的最佳方法(简单)是什么?我想转换为数组,然后用 JsonView 输出它。我可以编写使用 get_object_var 的函数,但是当实体具有下一个实体集合时会出现问题。

Regards.

问候。

回答by Aurelijus Rozenas

Not sure about Zend, but in SF2 + Doctrine you can use getValues()method.

不确定 Zend,但在 SF2 + Doctrine 中你可以使用getValues()method。

$asArray = $persistentCollection->getValues();

回答by Guilherme Blanco

I'll decouple the answer in 2 parts, mainly because you haven't clarified enough if you want to solve purely the PersistentCollection or the entire graph serialization.

我将把答案分为 2 部分,主要是因为你没有足够澄清,如果你想纯粹解决 PersistentCollection 或整个图序列化。

1- Assuming you already know how to solve Entity's serialization, the PersistentCollection can be turned into an array of Entities by calling toArray() method.

1- 假设您已经知道如何解决实体的序列化,那么可以通过调用 toArray() 方法将 PersistentCollection 转换为实体数组。

2- Assuming you don't, I suggest you to either use a pre-built library like JMS Serializer. If you want to create your own by hand, use the ClassMetadata instance that can be extracted from EntityManager->getClassMetadata(get_class($someEntity)) and iterating through fieldMappings and associationMappings properties.

2- 假设你没有,我建议你要么使用像JMS Serializer这样的预构建库。如果您想手动创建自己的,请使用 ClassMetadata 实例,该实例可以从 EntityManager->getClassMetadata(get_class($someEntity)) 中提取并遍历 fieldMappings 和 associationMappings 属性。