Doctrine2, PersistentCollection and JMS Serializer

我的梦境 提交于 2019-12-01 08:15:40

问题


I have an Entity with a oneToMany relationship, I can get the associated items using;

$this->getQueuedItems()

This returns Doctrine\ORM\PersistentCollection object, I am then passing this to JMS Serializer like so;

$serializer = $container->get('serializer');
$json = $serializer->serialize($this->getQueuedItems(), 'json');

But outputting $json using var_dump() results in;

string(2) "[]"

Which is wrong. There is data there, because if I do a foreach() over $this->getQueuedItems() I get data.

How can I use JMS Serializer to serialise Doctrine\ORM\PersistentCollection into JSON?

Thanks


回答1:


The PersistentCollection object is an Iterator Aggregate and not an array. The distinction is that an Iterator is an object that can be iterated over and so may or may not contain the data required for serializing to an array at any one time.

To serialize the Collection as JSON, try the following:

$serializer = $container->get('serializer');
$arr        = $this->getQueuedItems()->toArray();
$json       = $serializer->serialize($arr, 'json');

If you're not too fussed about the keys, you could also use getValues, rather than toArray.



来源:https://stackoverflow.com/questions/15257769/doctrine2-persistentcollection-and-jms-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!