第二次计数分页查询

时间:2014-08-06 09:01:36

标签: php symfony

我有几个相当复杂的查询,对于每个查询,我都要写第二个查询计算结果。例如,在模型中:

$dql = "SELECT u FROM AcmeBundle:Users u LEFT JOIN AcmeBundle:Products p WITH u.id = p.id";

我必须像这样创建一个重复的查询:

$countingQuery = "SELECT COUNT(u.id) FROM AcmeBundle:Users u LEFT JOIN AcmeBundle:Products p WITH u.id = p.id";

主要问题是,对于第一个查询中的每个更改,我都必须更改第二个查询。

所以我提出了另一个想法:

$countingSelect = "SELECT COUNT(u.id)";

$noncountingSelect = "SELECT u";

$dql = " FROM AcmeBundle:Users u LEFT JOIN AcmeBundle:Products p WITH u.id = p.id";

return $this->getEntityManager()->createQuery($noncountingSelect . $dql)
->setHint('knp_paginator.count', $this->getEntityManager()->createQuery($countingSelect . $dql)->getSingleScalarResult());

它当然有效,但是对于更大的选择,解决方案似乎相当丑陋。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我相信Doctrine \ ORM \ Tools \ Pagination \ Paginator会做你想要的,没有额外的复杂性。

$paginator = new Paginator($dql);
$paginator
    ->getQuery()
    ->setFirstResult($pageSize * ($currentPage - 1)) // set the offset
    ->setMaxResults($pageSize); // set the limit

$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $paginator->getMaxResults());

代码来自:http://showmethecode.es/php/doctrine2/doctrine2-paginator/

答案 1 :(得分:0)

您可以按the docs中的说明创建客户存储库,并将您的查询添加到具有次要编辑功能的客户存储库中。

use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{
    public function findProducts()
    {
        return $this->findProductsOrCountProducts();
    }

    public function findCountProducts()
    {
        return $this->findProductsOrCountProducts(true);
    }

    private function findProductsOrCountProducts($count = false)
    {
        $queryBuilder = $this->createQueryBuilder('u');

        if ($count) {
            $queryBuilder->select('COUNT(u.id)');
        }

        $query = $queryBuilder
            ->leftJoin('AcmeBundle:Products', 'p', 'WITH', 'u.id = p.id')
            ->getQuery()
        ;

        if ($count) {
            return $query->getSingleScalarResult();
        } else {
            return $query->getResult();
        }
    }
}

然后您可以使用...

调用您的方法
$repository = $this->getDoctrine()
    ->getRepository('AcmeBundle:Users');

// for products
$products = $repository->findProducts();
// for count
$countProducts = $repository->findCountProducts();

注意:

我知道最好不要只是在这里查看客户存储库位的文档'YAML映射...

# src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.yml
Acme\StoreBundle\Entity\Product:
    type: entity
    repositoryClass: Acme\StoreBundle\Entity\ProductRepository
    # ...