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



用例:我想将搜索查询和结果总数存储到数据库中,以便我可以看到人们正在搜索的内容在我的应用程序中不存在。

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

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

错误:

可捕获的致命错误:类的对象 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: []
}

你应该这样做

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

事实上,$pagination属于阶级KnpBundlePaginatorBundlePaginationSlidingPagination这是父类的代码KnpComponentPagerPaginationAbstractPaginationhttps://github.com/KnpLabs/knp-components/blob/master/src/Knp/Component/Pager/Pagination/AbstractPagination.php#L118:L121

相关内容

  • 没有找到相关文章