12
12
namespace App \Repository ;
13
13
14
14
use App \Entity \Post ;
15
+ use App \Entity \Tag ;
15
16
use Doctrine \Bundle \DoctrineBundle \Repository \ServiceEntityRepository ;
16
17
use Doctrine \Common \Persistence \ManagerRegistry ;
17
18
use Doctrine \ORM \Query ;
@@ -35,21 +36,22 @@ public function __construct(ManagerRegistry $registry)
35
36
parent ::__construct ($ registry , Post::class);
36
37
}
37
38
38
- public function findLatest (int $ page = 1 ): Pagerfanta
39
+ public function findLatest (int $ page = 1 , Tag $ tag = null ): Pagerfanta
39
40
{
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 );
53
55
}
54
56
55
57
private function createPaginator (Query $ query , int $ page ): Pagerfanta
0 commit comments