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

How do I get total count for a search query in the controller in Symfony

用例:我想将搜索查询和结果总数存储到数据库中,这样我就可以看到人们正在搜索的内容在我的数据库中不存在申请。

有效的方法:我能够获取并存储查询,但我不知道如何获取搜索结果的总数。

这是控制器的代码示例。当我目前尝试这个时,我得到以下

error:Catchable Fatal Error: Object of class Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination could not be converted to string

我尝试通过请求 $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]);

    }

这是在 twig 模板上输出的变量转储:

 "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: []
  }

你应该做

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

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