Counting comments
We still need to make some cosmetic changes. Posts with a lot of comments interest many readers. It would be better if the number of comments for each post was available directly from the list page. Doctrine can populate an array containing the result of the call to an aggregate
function as the first row and hydrated entities as the second.
Add the following method, for retrieving posts with the associated comments, to the PostRepository
class:
/** * Finds posts with comment count * * @return array */ public function findWithCommentCount() { return $this ->createQueryBuilder('p') ->leftJoin('p.comments', 'c') ->addSelect('COUNT(c.id)') ->groupBy('p.id') ->getQuery() ->getResult() ; }
Thanks to the GROUP BY
clause and the call to addSelect()
, this method will return a two-dimensional array instead of an array of the Post
entities. Arrays...