2014-12-17 3 views
0
에게 반환에서 doctrine2을 방지하기 위해

내가 코딩 한 것은 교리어떻게 특정 필드

한 사용자와 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": "[email protected]", 
     "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": "[email protected]", 
    "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" 
} 
] 

를 반환 것입니다 oint, 알맞은 특정 사용자의 알림을 반환합니다. 성도 및 성 같은 특정 필드가 사용자에게 필요하므로 반환 된 데이터를 응용 프로그램에서 사용할 수 있습니다. 그러나 doctrine은 토큰과 사용자가 알 필요가없는 정보와 함께 해시 된 암호와 소금을 반환합니다.

어떻게 doctrine이 필드를 반환하지 않겠다고 말합니까?

답변

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 

주어진 예에서, 나열되지 않은 모든 속성은 제외된다.

+0

첫 번째 코드는 어떤 이유로 무한 루프를 반환했지만 JMS 번들은 – user3531149

+0

@ user3531149 덕분에 해결되었습니다. 문서에서 직접 추측 한 것 자체는 기본 Serializer를 사용하지 않았습니다. – kix

3

custom repository class을 만들어야합니다. 당신이 partial object syntax 사용할 수있는 DQL 쿼리에 대한

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

:이 클래스에서

는이 같은 방법을 만들 수 있습니다.

+2

어떤 이유에서든 Doctrine의'Paginator'를 사용하고 싶다면 별도의 필드가 아닌'PARTIAL' 문법을 사용해야합니다. –