我没有在这个主题上找到任何特别的东西,并且Doctrine文档在分页上非常不稳定所以在这里:
我在Laravel 4上使用了Doctrine 2.我正在努力让分页工作,并且已经返回第一页结果,如此:
public function paginate($query, $page_size, $current_page){
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$total_results = count($paginator);
$pagesCount = ceil($total_results / $page_size);
// now get one page's items:
$paginator
->getQuery()
->setFirstResult($page_size * ($current_page-1)) // set the offset
->setMaxResults($page_size); // set the limit
foreach ($paginator as $pageItem) {
$results[] = $pageItem;
}
return $results;
}
但这只适用于第一页。当我想点击结果页面'n'时,我不知道如何开始这个。我没有找到任何存储DQL查询的方法(它不能传递给视图或存储在会话变量中)。
有什么想法吗?
答案 0 :(得分:0)
好吧,我在我的应用程序中使用了doctrine和laravel。看看:
public function paginate($pageNumber = 1, $recordsPerPage = 20)
{
// updating page number according to records per page
$pageNumber = ($pageNumber == 1)? 0 : (($pageNumber -1) * 20);
/** @var $qb QueryBuilder $qb */
$qb = \Doctrine::createQueryBuilder();
$qb->select('m');
$qb->from('models\MyModel', 'm');
$qb->orderBy('m.name', 'asc');
$qb->setMaxResults($recordsPerPage);
$qb->setFirstResult($pageNumber);
$records = $qb->getQuery()->getResult();
// creating the paginator with the results
$paginator = \Paginator::make($records, $this->totalOfRecords(), $recordsPerPage);
$paginator->setBaseUrl('my-paginator-url');
// HERE you can do some stuff with the $paginator and $records vars
}
public function totalOfRecords()
{
/** @var $qb QueryBuilder $qb */
$qb = \Doctrine::createQueryBuilder();
$qb->select('count(m)');
$qb->from('models\MyModel', 'm');
// return total of records
return $qb->getQuery()->getSingleScalarResult();
}
然后,你可以这样做:
// paginate the first page with 10 records per page (showing records from 0 to 9)
$this->paginate(1, 10);
// paginate the third page with 20 records per page (showing records from 30 to 49)
$this->paginate(3, 20);