Перейти к основному содержанию

ЧПУ разбивка на страницы

Задача - разбить большой объем записей на страницы, при этом доступ не в виде параметра в запросе, а в виде страницы.

Зададим начальный url, в котором укажем лимит на количество записей и смещение

@Route("/products/{limit}/{offset}", name="products"),

далее из

$request->attributes

получаем эти значения. Используя компонент paginator разбиваем на страницы

$paginator  = new \Doctrine\ORM\Tools\Pagination\Paginator($query);

$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);

// now get one page's items:
$paginator
    ->getQuery()
    ->setFirstResult($pageSize * ($currentPage-1)) // set the offset
    ->setMaxResults($pageSize); // set the limit

foreach ($paginator as $pageItem) {
    echo "<li>" . $pageItem->getName() . "</li>";
}

2

<?php
use Doctrine\ORM\Tools\Pagination\Paginator;

$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
                       ->setFirstResult(0)
                       ->setMaxResults(100);

$paginator = new Paginator($query, $fetchJoinCollection = true);

$c = count($paginator);
foreach ($paginator as $post) {
    echo $post->getHeadline() . "\n";
}

3

/**
 * We have this `getAllPosts()` function
 * We want to paginate the results using doctrines Pagination tool.
 */
public function getAllPosts()
{
    $query = $this->createQueryBuilder('p')
        ->orderBy('p.created', 'DESC')
        ->getQuery();

    $query->getResult();
}

// Place this is your repository (or where ever the query is constructed)
use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 * Our new getAllPosts() method
 *
 * 1. Create & pass query to paginate method
 * 2. Paginate will return a `\Doctrine\ORM\Tools\Pagination\Paginator` object
 * 3. Return that object to the controller
 *
 * @param integer $currentPage The current page (passed from controller)
 *
 * @return \Doctrine\ORM\Tools\Pagination\Paginator
 */
public function getAllPosts($currentPage = 1)
{
    // Create our query
    $query = $this->createQueryBuilder('p')
        ->orderBy('p.created', 'DESC')
        ->getQuery();

    // No need to manually get get the result ($query->getResult())

    $paginator = $this->paginate($query, $currentPage);

    return $paginator;
}

/**
 * Paginator Helper
 *
 * Pass through a query object, current page & limit
 * the offset is calculated from the page and limit
 * returns an `Paginator` instance, which you can call the following on:
 *
 *     $paginator->getIterator()->count() # Total fetched (ie: `5` posts)
 *     $paginator->count() # Count of ALL posts (ie: `20` posts)
 *     $paginator->getIterator() # ArrayIterator
 *
 * @param Doctrine\ORM\Query $dql   DQL Query Object
 * @param integer            $page  Current page (defaults to 1)
 * @param integer            $limit The total number per page (defaults to 5)
 *
 * @return \Doctrine\ORM\Tools\Pagination\Paginator
 */
public function paginate($dql, $page = 1, $limit = 5)
{
    $paginator = new Paginator($dql);

    $paginator->getQuery()
        ->setFirstResult($limit * ($page - 1)) // Offset
        ->setMaxResults($limit); // Limit

    return $paginator;
}

4

use Doctrine\ORM\Tools\Pagination\Paginator;

$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
                   ->setFirstResult(0)
                   ->setMaxResults(100);

$paginator = new Paginator($query, $fetchJoinCollection = true);

$c = count($paginator);
foreach ($paginator as $post) {
    echo $post->getHeadline() . "\n";
}

5

/**
 * @Route("/users/{page}", name="user_list", requirements={"page"="\d+"})
 */
public function getUsersByPage($page = 1)
{
    // get entity manager
    $em = $this->getDoctrine()->getManager();

    // get the user repository
    $developers = $em->getRepository(Users::class);

    // build the query for the doctrine paginator
    $query = $developers->createQueryBuilder('u')
                        ->orderBy('d.id', 'DESC')
                        ->getQuery();

    //set page size
    $pageSize = '100';

    // load doctrine Paginator
    $paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);

    // you can get total items
    $totalItems = count($paginator);

    // get total pages
    $pagesCount = ceil($totalItems / $pageSize);

    // now get one page's items:
    $paginator
        ->getQuery()
        ->setFirstResult($pageSize * ($page-1)) // set the offset
        ->setMaxResults($pageSize); // set the limit

    foreach ($paginator as $pageItem) {
        // do stuff with results...
        dump($pageItem);
    }

    // return stuff..
    return [$userList, $totalItems, $pageCount];
}