emkay
emkay

Reputation: 901

Return only specific fields in API call in Symfony

I need to return a list of photos as part of an API endpoint.

However, when I try to return the list of objects returned by Symfony's query builder, it returns all CHILD data which each photo object as well, e.g. data pertaining to user attached to the photo. This bloats the returned data severely.

How can I select or filter the list of objects so that my API endpoint only returns specific fields?

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

}

Upvotes: 0

Views: 598

Answers (1)

Valery K.
Valery K.

Reputation: 147

You can use something like this: ... $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);

Upvotes: 1

Related Questions