我编码的是与教义
的oneToMany关系一个用户--->有很多通知
这是我获取数据的方式
/**
* @Route("/test")
*/
public function testRoute()
{
//get the user notifications
$notifications = $this->getUser()->getNotifications();
//return json response
$serializer = $this->get('serializer');
$json = $serializer->serialize($notifications, 'json');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
这是控制器返回的内容
[
{
"id": 1,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2I==",
"email": "ga@ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"salt": "Lqch0N84UH1QmFI5O",
"form_token": "sO6NgWd",
"is_active": true,
"registration_confirmation": "success",
"secret_confirmation_id": "qTwNGm4CSKHzJOe8ry9DcXavt",
"socket_token": "KuMlxYHa"
},
"created_at": "2014-12-16T13:36:20+0100",
"link_to": "#test"
},
{
"id": 2,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2IYX1DONLA/70a8hzMUQ==",
"email": "ga@ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"profile_rank": "Beginner", (...)
},
"created_at": "2014-12-16T13:36:24+0100",
"link_to": "#test"
}
]
我认为你明白了,它会返回某个用户的通知,这是正常的, 我还需要用户的某些字段,如lastname和firstname,因此返回的数据在应用程序中可用。 但是,学说还会返回散列密码和盐以及用户不需要知道的令牌和信息。
我如何告诉学说不要返回这些字段或者不用它们来开始?
答案 0 :(得分:3)
这与Doctrine无关,这是尝试获取并返回所有可用值的默认Serializer
。
查看Serializer component documentation以了解如何忽略属性。基本上,您必须将规范化器传递给序列化程序的构造函数:
<?php
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
$normalizer = new GetSetMethodNormalizer();
$normalizer->setIgnoredAttributes(array('age'));
$encoder = new JsonEncoder();
$serializer = new Serializer(array($normalizer), array($encoder));
$serializer->serialize($person, 'json');
此外,我强烈建议您切换到JMSSerializer和/或使用FOSRestBundle,因为它为序列化提供了更大的灵活性。属性列表针对上下文进行配置,并具有基本排除策略。这样,您只需要列出要公开的属性,而不是排除:
AppBundle\Entity\Car:
exclusion_policy: all
properties:
id:
expose: true
vendor:
expose: true
title:
expose: true
在给定的示例中,将排除未列出的所有属性。
答案 1 :(得分:3)
您应该创建custom repository class。
在这个类中创建一个这样的方法:
// src/AppBundle/Entity/NotificationRepository.php
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
class NotificationRepository extends EntityRepository
{
public function findAllByUser()
{
return $this->getEntityManager()
->createQuery(
'SELECT [only the fields you need] FROM [....]'
)
->getResult();
}
}
对于DQL查询,您可以使用partial object syntax。