Symfony - 手动添加其他字段

时间:2018-06-13 08:32:55

标签: php function symfony

我写了一个查询来从db返回所有数据。现在,我需要添加一个额外的字段。 api调用应该接收一个额外的字段 - " term"。当术语通过时,结果将被过滤以匹配该术语。

我的服务。

/**
 * Return all schools from city
 *
 * @param int $limit
 * @param int $offset
 * @return array
 */
public function getCityPaginated($limit = 20, $offset = 0)
{

    $query = $this->getCityRepository()
        ->createQueryBuilder('c')
        ->getQuery();

    return $this->container->get('paginator')->paginate($query, $offset, $limit);
}

我的控制器..

/**
 * @Route("/cities", name="city_list")
 * @throws \Doctrine\Common\Annotations\AnnotationException
 */
public function getCityPaginatedAction()
{
    if(isset($this->data['offset'])){
        $offset = $this->data['offset'];
    }else {
        $offset = 0;
    }

    if(isset($this->data['limit'])){
        $limit = $this->data['limit'];
    }else{
        $limit = 20;
    }

    $city = $this->get('city')->getCityPaginated($limit, $offset);

    return $this->success($city, ['city_data']);
}

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要获得一个POST参数吗?

public function getCityPaginatedAction(Request $request)
{
   $term = $request->request->get('term');

答案 1 :(得分:0)

更改控制器,以便您从请求中读取term参数并将其传递给服务方法:

/**
 * @Route("/cities", name="city_list")
 * @param Request $request
 * @throws \Doctrine\Common\Annotations\AnnotationException
 */
public function getCityPaginatedAction(Request $request)
{
    if(isset($this->data['offset'])){
        $offset = $this->data['offset'];
    }else {
        $offset = 0;
    }

    if(isset($this->data['limit'])){
        $limit = $this->data['limit'];
    }else{
        $limit = 20;
    }

    $term = $request->query->get('term');
    $city = $this->get('city')->getCityPaginated($limit, $offset, $term);

    return $this->success($city, ['city_data']);
}

然后,更改您的服务以在查询中使用此参数

/**
 * Return all schools from city
 *
 * @param int $limit
 * @param int $offset
 * @param string $text
 * @return array
 */
public function getCityPaginated($limit = 20, $offset = 0, $term = null)
{
    $queryBuilder = $this->getCityRepository()
        ->createQueryBuilder('c');

    if ($term) {
        $queryBuilder->andWhere($queryBuilder->expr()->like('c.name', :term)
            ->setParameter('term', "%" . $term . "%");
    }

    $query = $queryBuilder->getQuery();

    return $this->container->get('paginator')->paginate($query, $offset, $limit);
}

您可能想要更改查询生成器并在其他字段上进行搜索。