1212namespace App \Repository ;
1313
1414use App \Entity \Post ;
15+ use App \Entity \Tag ;
1516use Doctrine \Bundle \DoctrineBundle \Repository \ServiceEntityRepository ;
1617use Doctrine \Common \Persistence \ManagerRegistry ;
1718use Doctrine \ORM \Query ;
@@ -35,21 +36,22 @@ public function __construct(ManagerRegistry $registry)
3536 parent ::__construct ($ registry , Post::class);
3637 }
3738
38- public function findLatest (int $ page = 1 ): Pagerfanta
39+ public function findLatest (int $ page = 1 , Tag $ tag = null ): Pagerfanta
3940 {
40- $ query = $ this ->getEntityManager ()
41- ->createQuery ('
42- SELECT p, a, t
43- FROM App:Post p
44- JOIN p.author a
45- LEFT JOIN p.tags t
46- WHERE p.publishedAt <= :now
47- ORDER BY p.publishedAt DESC
48- ' )
49- ->setParameter ('now ' , new \DateTime ())
50- ;
51-
52- return $ this ->createPaginator ($ query , $ page );
41+ $ qb = $ this ->createQueryBuilder ('p ' )
42+ ->addSelect ('a ' , 't ' )
43+ ->innerJoin ('p.author ' , 'a ' )
44+ ->leftJoin ('p.tags ' , 't ' )
45+ ->where ('p.publishedAt <= :now ' )
46+ ->orderBy ('p.publishedAt ' , 'DESC ' )
47+ ->setParameter ('now ' , new \DateTime ());
48+
49+ if (null !== $ tag ) {
50+ $ qb ->andWhere (':tag MEMBER OF p.tags ' )
51+ ->setParameter ('tag ' , $ tag );
52+ }
53+
54+ return $ this ->createPaginator ($ qb ->getQuery (), $ page );
5355 }
5456
5557 private function createPaginator (Query $ query , int $ page ): Pagerfanta
0 commit comments