仅返回Symfony中API调用中的特定字段


Return only specific fields in API call in Symfony

我需要返回一个照片列表,作为API端点的一部分。

然而,当我试图返回Symfony的查询生成器返回的对象列表时,它会返回每个照片对象的所有CHILD数据,例如与照片所附用户有关的数据。这使返回的数据严重膨胀。

如何选择或筛选对象列表,使API端点仅返回特定字段?

public function getManyAction(Request $request, $card_id) {
    $photos = $this->getDoctrine()->getRepository('AppBundle:Photo')->findByCard($card_id);
    if($photos)  {
        $response = $this->serializeResponseToJson(true, null, $photos);
    }
    else{
        $response = $this->serializeResponseToJson(false, "No photos were found for this card");
    }
    return new JsonResponse($response);
}

您可以使用以下内容: ... $em=$this->getDoctrine()->getManager(); $query=$em->createQuery('SELECT p.field1,p.field2,p.field3 FROM AppBundle:Photo p WHERE p.card=:card')->setParameter('card',$card_id); $photos=$query->getResult(); ... return new JsonResponse($response);