Search code examples
doctrine-ormdoctrineknppaginator

How to get query based on Repository / Criteria in Doctrine?


How in Doctrine may I get a query based on Criteria?

I have the following Doctrine Criteria set:

$criteria = Criteria::create();
$criteria->where(Criteria::expr()->eq("versionFinale", true))
    ->andWhere(Criteria::expr()->eq("versionSoftDeleted", false))
    ->andWhere(Criteria::expr()->eq("versionStatus", "PUBLISHED"));

Normally I would use the following code to get results:

$repo->matching($criteria)

However, as I want to use KNP Paginator I need a query.

I could use:

$this->createQueryBuilder('a')
     ->addCriteria($criteria);

However this would require me to provide repo in query builder which would not be very elegant and efficient.

How may I get query based on repository & criteria?


Solution

  • What is not elegant in creating some sort of PaginatorQueryService? Simply implement something like this(not tested)

    class PaginatorQueryService
    {
        private $em;
    
        function __construct(EntityManagerInterface $em)
        {
            $this->em = $em;
        }
    
        public function getPaginatorQuery($repository, $criteria)
        {
           return $this->em->createQueryBuilder()->select('entity')->from($repository, 'entity')->addCriteria($criteria)->getQuery();
        }
    }