Reduce number of queries on tag list

This commit is contained in:
Nicolas Hart 2017-08-06 21:58:14 +02:00
parent f11a3cf21c
commit 935e9fffb4
3 changed files with 23 additions and 39 deletions

View file

@ -84,28 +84,11 @@ class TagController extends Controller
*/
public function showTagAction()
{
$repository = $this->get('wallabag_core.entry_repository');
$tags = $this->get('wallabag_core.tag_repository')
->findAllTags($this->getUser()->getId());
$flatTags = [];
foreach ($tags as $tag) {
$nbEntries = $repository->countAllEntriesByUserIdAndTagId(
$this->getUser()->getId(),
$tag->getId()
);
$flatTags[] = [
'id' => $tag->getId(),
'label' => $tag->getLabel(),
'slug' => $tag->getSlug(),
'nbEntries' => $nbEntries,
];
}
->findAllFlatTagsWithNbEntries($this->getUser()->getId());
return $this->render('WallabagCoreBundle:Tag:tags.html.twig', [
'tags' => $flatTags,
'tags' => $tags,
]);
}

View file

@ -329,26 +329,6 @@ class EntryRepository extends EntityRepository
return (int) $qb->getQuery()->getSingleScalarResult();
}
/**
* Count all entries for a tag and a user.
*
* @param int $userId
* @param int $tagId
*
* @return int
*/
public function countAllEntriesByUserIdAndTagId($userId, $tagId)
{
$qb = $this->createQueryBuilder('e')
->select('count(e.id)')
->leftJoin('e.tags', 't')
->where('e.user=:userId')->setParameter('userId', $userId)
->andWhere('t.id=:tagId')->setParameter('tagId', $tagId)
;
return (int) $qb->getQuery()->getSingleScalarResult();
}
/**
* Remove all entries for a user id.
* Used when a user want to reset all informations.

View file

@ -62,6 +62,27 @@ class TagRepository extends EntityRepository
return $tags;
}
/**
* Find all tags (flat) per user with nb entries.
*
* @param int $userId
*
* @return array
*/
public function findAllFlatTagsWithNbEntries($userId)
{
return $this->createQueryBuilder('t')
->select('t.id, t.label, t.slug, count(e.id) as nbEntries')
->distinct(true)
->leftJoin('t.entries', 'e')
->where('e.user = :userId')
->groupBy('t.id')
->orderBy('t.slug')
->setParameter('userId', $userId)
->getQuery()
->getArrayResult();
}
/**
* Used only in test case to get a tag for our entry.
*