<?php

namespace SymfonyDay\Bundle\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    public function getPublishedPost($id)
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->andWhere('p.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->getQuery()
            ->execute()
        ;
    }

    private function getActivePostsQueryBuilder($alias)
    {
        return $this
            ->createQueryBuilder($alias)
            ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date')
            ->setParameter('date', date('Y-m-d H:i'))
        ;
    }
}
<?php

namespace SymfonyDay\Bundle\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    public function getPublishedPost($id)
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->select('p, c')
            ->leftJoin('p.comments', 'c')
            ->andWhere('p.id = :id')
            ->andWhere('c.isPublished = :published')
            ->setParameter('id', $id)
            ->setParameter('published', true)
            ->getQuery()
            ->getSingleResult()
        ;
    }

    public function getMostRecentPosts()
    {
        return $this
            ->getActivePostsQueryBuilder('p')
            ->getQuery()
            ->execute()
        ;
    }

    private function getActivePostsQueryBuilder($alias)
    {
        return $this
            ->createQueryBuilder($alias)
            ->andWhere('p.publishedAt IS NULL OR p.publishedAt <= :date')
            ->setParameter('date', date('Y-m-d H:i'))
        ;
    }
}
Decrease the query count when loading a blog post
Decrease the query count when loading a blog post
