如何在Symfony的控制器中获取搜索查询的总计数

时间:2018-05-15 19:01:47

标签: php symfony controller knppaginator knppaginatorbundle

用例:我想将搜索查询和结果总数存储到数据库中,这样我就可以看到人们搜索的内容并不存在于我的应用程序中。< / p>

工作正常:我能够获取并存储查询,但我无法弄清楚如何获取搜索结果的总数。

以下是Controller的代码示例。当我今天尝试这个时,我得到以下

  

错误:可捕获的致命错误:类的对象   Knp \ Bundle \ PaginatorBundle \ Pagination \ SlidingPagination不可能   转换为字符串

我已尝试通过请求$ pagination [totalCount]来处理像数组一样的$ pagination,但这只是返回null。

 public function fpcAction(Request $request)
    {

            $query = dump($request->query->get('q'));

            $finder = $this->container->get('fos_elastica.finder.app.product');
            $page = $request->query->getInt('page', 1);

            $paginator = $this->get('knp_paginator');
            $results = $finder->createPaginatorAdapter($query);
            $pagination = $paginator->paginate($results, $page, 12);



            $searchmetrics = new SearchTerms();
            $searchmetrics->setSearchterm($query);
            $searchmetrics->setDate(time());

            // TODO: Need to get the total qty of search results for this specific query
            $searchmetrics->setResultsqty($pagination);

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($searchmetrics);
            $entityManager->flush();


            return $this->render('default/search.html.twig', ['searchresults' => $pagination, 'query' => $query]);

    }

这是变量的转储,因为它在树枝模板上输出:

 "searchresults" => SlidingPagination {#1028 ▼
    -route: "search"
    -params: array:1 [▶]
    -pageRange: 5
    -template: "@KnpPaginator/Pagination/sliding.html.twig"
    -sortableTemplate: "@KnpPaginator/Pagination/sortable_link.html.twig"
    -filtrationTemplate: "@KnpPaginator/Pagination/filtration.html.twig"
    #currentPageNumber: 1
    #numItemsPerPage: 12
    #items: array:12 [▶]
    #totalCount: 8104
    #paginatorOptions: array:6 [▶]
    #customParameters: []
  }

1 个答案:

答案 0 :(得分:3)

你应该做

$searchmetrics->setResultsqty($pagination->getTotalItemCount());

事实上,$pagination属于Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination类  这是父类Knp\Component\Pager\Pagination\AbstractPagination https://github.com/KnpLabs/knp-components/blob/master/src/Knp/Component/Pager/Pagination/AbstractPagination.php#L118:L121

的代码