【问题标题】:How to put pagination on search result using symfony2?如何使用 symfony2 对搜索结果进行分页?
【发布时间】:2015-07-28 18:36:02
【问题描述】:

我正在使用 symfony2 开发一个项目。我已经有了我的搜索功能,它已经在工作了。但我想要的是对搜索结果进行分页,因为有时要检索大量数据。我怎么可能做到呢?

这是我的代码:

public function searchAction (Request $request) {

        $request = $this->getRequest();
        $data = $request->get('search');

        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery (
            'SELECT a,b,c FROM SampleBundle:transactDetail a
            JOIN a.transact b
            JOIN b.transactType c
            WHERE b.pNumber LIKE :data
            OR b.senderId LIKE :data'
        )
        ->setParameter('data', "%$data%");
        $result = $query->getResult();

        if ($result == null ) {
            return $this->render('SampleBundle:Sample:noresult.html.twig');
        }
        return $this->render('SampleBundle:Sample:search.html.twig', array('result' => $result));
    }

提前致谢。

【问题讨论】:

  • 有人能帮帮我吗?
  • 您可以使用 KnpPaginator 或 FantaPaginator,它们有适用于 Doctrine、Propel 等的适配器。或者只是使用 DoctrinePaginator(内置于学说组件),但它只分页,它没有分页 html 组件的渲染器。
  • @aizele 你可以使用PagerFantaBundle
  • 我只是在使用“使用 Doctrine\ORM\Tools\Pagination\Paginator”。我该如何实现它?
  • @KarolWojciechowski:我如何在 Doctrine Paginator 中做到这一点?你能帮帮我吗?

标签: php symfony pagination


【解决方案1】:

这是带有Paginator 的代码示例:

public function searchAction(Request $request, $firstResult = 0, $maxResults = 100)
{
    $request = $this->getRequest();
    $data = $request->get('search');

    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
        'SELECT a,b,c FROM SampleBundle:transactDetail a
            JOIN a.transact b
            JOIN b.transactType c
            WHERE b.pNumber LIKE :data
            OR b.senderId LIKE :data'
    )
        ->setParameter('data', "%$data%")
        ->setFirstResult($firstResult)
        ->setMaxResults($maxResults);

    $result = new Paginator($query);

    if ($result == null) {
        return $this->render('SampleBundle:Sample:noresult.html.twig');
    }

    return $this->render('SampleBundle:Sample:search.html.twig', array('result' => $result));
}

如果您想计算总数,只需 count($result);
Paginator 具有 Countable 和 IteratorAggregate 接口。
所以你可以毫无问题地循环你的结果。

【讨论】:

  • 路由怎么样?我还需要做这样的事情吗: sample_search : pattern : /search/{$firstResult} defaults: { _controller: "SampleBundle:Sample:search", firstResult: 1 } ?
  • 我可以将我的代码(查询)移动到存储库,这样它在我的控制器中不会太长吗?可能吗?我该怎么做?谢谢:)
  • 如何在视图中显示分页导航?
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 2018-05-28
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多