Start your All-Access Pass to unlock this challenge
Imagine we have the following code in a Twig template:
{% for product in category.products %}
{{ product.name }}
{% endfor %}
To fetch the Category
object, in the controller, we call this method on CategoryRepository
:
public function findBySlug(string $slug): ?Category
{
return $this->createQueryBuilder('category')
->andWhere('category.slug = :slug')
->setParameter('slug', $slug);
->getQuery()
->getOneOrNullResult();
}
}
But when I load the page... I have 11 queries just to render 10 products! Yikes! To try to fix this, I made this change:
public function findBySlug(string $slug): ?Category
{
return $this->createQueryBuilder('category')
->andWhere('category.slug = :slug')
->setParameter('slug', $slug);
+ ->leftJoin('category.product', 'product')
+ ->addSelect('product')
->getQuery()
->getOneOrNullResult();
}
}
Will this reduce my queries? And, do I need to tweak any other parts of my code?