Symfony 5: Mastering Doctrine Relations
Joining Across a Relationship & The N + 1 Problem
Start your All-Access Pass to unlock this challenge
Buy Access Login

Challenge 1 / 1

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?

Select your answer
Skip challenges and go to theNext Chapter

Turn Challenges Off?

All further challenges will be skipped automatically.
You can re-enable challenges at any time on this page or from your account page.