简体   繁体   English

如何防止doctrine2返回某些字段

[英]How to to prevent doctrine2 from returning certain fields

What I have coded is a oneToMany relationship with doctrine 我编写的是与教义的一对多关系

one user ---> has many notifications 一个用户--->有很多通知

This is how I get the data 这就是我获取数据的方式

/**
 * @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;
}

This is what the controller returns 这是控制器返回的内容

    [
{
    "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"
}
]

I think you get the point, it returns the notifications of a certain user which is allright, I also need certain fields from the user, like the lastname and the firstname, so the returned data is usable in the application. 我想您明白了,它可以返回某个用户的通知,这还不错,我还需要该用户的某些字段,例如姓氏和名字,因此返回的数据可在应用程序中使用。 But doctrine also returns the hashed password and the salt along with tokens and information the user doesn't need to know. 但是,学说还会返回散列的密码和盐以及用户不需要知道的令牌和信息。

how do I tell doctrine not to return those fields or not to fetch them to begin with? 我如何告诉教义不要返回这些字段或不先获取它们?

This is not about Doctrine, this is the default Serializer that tries to fetch and return all of the values available. 这与教义无关,这是默认的Serializer ,尝试获取并返回所有可用值。

Take a look at the Serializer component documentation to understand how to ignore properties. 查看Serializer组件文档,以了解如何忽略属性。 Basically, you'll have to pass a normalizer into your serializer's constructor: 基本上,您必须将规范化器传递给序列化器的构造函数:

<?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');

Also, I'd strongly suggest to switch to JMSSerializer and/or use FOSRestBundle , as it gives a lot more flexibility for the serialization. 另外,我强烈建议切换到JMSSerializer和/或使用FOSRestBundle ,因为它为序列化提供了更大的灵活性。 The property list is configured against contexts, and has base exclusion strategies. 属性列表是根据上下文配置的,并具有基本排除策略。 This way, you'd only need to list properties to expose, not to exclude: 这样,您只需要列出要公开的属性,而不必排除:

AppBundle\Entity\Car:
  exclusion_policy: all
  properties:
    id:
      expose: true
    vendor:
      expose: true
    title:
      expose: true

In the given example, all properties that were not listed would be excluded. 在给定的示例中,所有未列出的属性都将被排除。

You should create a custom repository class . 您应该创建一个自定义存储库类

In this class create a method like this: 在此类中,创建一个如下所示的方法:

// 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();
    }
}

For the DQL query you could use the partial object syntax . 对于DQL查询,可以使用部分对象语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM