【问题标题】:Return only specific fields in API call in Symfony在 Symfony 中仅返回 API 调用中的特定字段
【发布时间】:2016-05-02 19:39:01
【问题描述】:

我需要返回一个照片列表作为 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);

}

【问题讨论】:

    标签: php api symfony


    【解决方案1】:

    你可以使用这样的东西: ... $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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多