我正在构建Symfony3项目。我正在使用JMS进行序列化。我有与Group
具有ManyToMany关系的User
实体。我正在尝试向Group
个对象添加其他数据。我正在使用序列化监听器来实现这一点。例如,我想让那个与当前用户一起去同一所学校的小组成员。我setData
将对象分组如下:
class SerializationListener{
//Constructor
/**
* @param ObjectEvent $event
*/
public function onGroupEntitySerialize(ObjectEvent $event)
{
if (!$this->currentUser) {
return;
}
/** @var GenericSerializationVisitor $visitor */
$visitor = $event->getVisitor();
$group = $event->getObject();
$groupMembersFromUserSchool = $this->em->getRepository('AppBundle:User')
->groupMembersFromUserSchool($group, $this->currentUser);
$visitor->setData('members', $groupMembersFromUserSchool);
$groupMembersCountFromUserSchool = count($groupMembersFromUserSchool);
$visitor->setData('memberCount', $groupMembersCountFromUserSchool);
}
}
然而,我得到了这个结果:
{
"items": [
{
"memberCount": 17,
"id": 1,
"name": "TestGroup1",
"members": [
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{}
]
}
]
}
因此隐藏了members
属性中的用户详细信息。我该如何显示它们?
class Group{
/**
* @Expose()
* @Groups({"group-details", "group-list"})
*/
protected $members;
}
class User{
/**
* @Expose()
* @Groups({"group-details", "group-list"})
*/
private $id;
/**
* @Expose()
* @Groups({"group-details", "group-list"})
*/
protected $name;
}
答案 0 :(得分:0)
参考source code here的文档,您只能添加integer|float|boolean|string|array
值:
/**
* Allows you to add additional data to the current object/root element.
* @deprecated use setData instead
* @param string $key
* @param integer|float|boolean|string|array|null $value This value must either be a regular scalar, or an array.
* It must not contain any objects anymore.
*/
public function addData($key, $value)
{
if (isset($this->data[$key])) {
throw new InvalidArgumentException(sprintf('There is already data for "%s".', $key));
}
所以尝试类似:
$arrayValuesOfMembers = // some data as array probably extracted by the repo methods
$visitor->setData('members', $arrayValuesOfMembers);
希望这个帮助