/symfony-skills:doctrine-query-optimizationfrom symfony-skills
Guides Doctrine query optimization in Symfony: fixes N+1 with JOIN FETCH, uses DTO hydration for read-only endpoints, and implements keyset pagination. Activates on N+1, slow query, DQL, hydration, or read model mentions.
Ships in symfony-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
One query for the parents + one query per parent for a lazy association = N+1. It hides in loops that touch a lazy relation.
// ❌ N+1 — every $order->getItems() fires a query
$orders = $repo->findBy(['status' => OrderStatus::Active]);
foreach ($orders as $order) {
$total = count($order->getItems()); // SELECT ... WHERE order_id = ? — N times
}
Fix A — JOIN FETCH (when you need the entities):
public function findActiveWithItems(): array
{
return $this->createQueryBuilder('o')
->addSelect('i') // hydrate items in the same query
->leftJoin('o.items', 'i')
->andWhere('o.status = :status')
->setParameter('status', OrderStatus::Active)
->getQuery()
->getResult();
}
When fetch-joining a to-many and paginating, use Doctrine's Paginator (it switches to a windowed two-query strategy so setMaxResults stays correct):
$query = $qb->setFirstResult($offset)->setMaxResults($limit)->getQuery();
$paginator = new Paginator($query, fetchJoinCollection: true);
Fix B — read-model DTO (when you only need to display): don't hydrate entities at all.
public function summaries(OrderStatus $status): array
{
return $this->createQueryBuilder('o')
->select(sprintf(
'NEW %s(o.id, o.customerEmail, o.status, o.createdAt)',
OrderSummary::class,
))
->andWhere('o.status = :status')
->setParameter('status', $status)
->getQuery()
->getResult(); // array of OrderSummary DTOs — no managed entities, no lazy loading
}
getResult() returns managed entities — most expensive (UoW tracks them).getArrayResult() / getScalarResult() — when you only read and never mutate.NEW (DTO hydration) — best for read endpoints; immutable, no identity map cost.// Offset pagination (fine for early pages)
$qb->setFirstResult($page * $perPage)->setMaxResults($perPage);
OFFSET scans and discards every skipped row — page 5,000 reads 100,000 rows to return 20. For deep pages / infinite scroll, use keyset (seek) pagination: filter by the last seen sortable key.
// ✅ Keyset — constant time regardless of depth. UUID v7 / createdAt are sortable.
public function pageAfter(?Uuid $lastId, int $limit): array
{
$qb = $this->createQueryBuilder('o')
->orderBy('o.id', 'DESC')
->setMaxResults($limit);
if ($lastId !== null) {
$qb->andWhere('o.id < :lastId')->setParameter('lastId', $lastId, 'uuid');
}
return $qb->getQuery()->getResult();
}
Index the sort key. With a tie-prone sort (createdAt), order by (createdAt DESC, id DESC) and seek on the tuple so the cursor is stable.
Don't load a million rows into memory. Iterate and clear the identity map periodically.
$query = $em->createQuery('SELECT o FROM App\Entity\Order o WHERE o.status = :s')
->setParameter('s', OrderStatus::Pending);
$batchSize = 500;
$i = 0;
foreach ($query->toIterable() as $order) {
$order->markStale();
if (++$i % $batchSize === 0) {
$em->flush();
$em->clear(); // detach everything, release memory
}
}
$em->flush();
$em->clear();
For inserts, enable JDBC-style batching and flush in chunks. Note: GenerationType.IDENTITY-style auto-increment forces a round-trip per row; UUID v7 keeps batching intact (another reason to use UUIDs).
EXISTS/SELECT 1 … setMaxResults(1) for existence checks, not count() of loaded rows.setMaxResults — wrap in Paginator(fetchJoinCollection: true).NEW DTO hydration.OFFSET for deep pagination — switch to keyset/seek on a sortable indexed key.toIterable() + periodic flush()/clear().count($repo->findBy(...)) to check existence — use an EXISTS/SELECT 1 query.WHERE/ORDER BY for keyset — add the index.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
n-plus-one, doctrine-orm, query-optimization, pagination, dto-hydration
npx claudepluginhub fatonh/symfony-skills --plugin symfony-skills17 skills in this plugin
/api-platform-resourcesUse when exposing data through API Platform 4 — defining #[ApiResource], operations, DTO resources, state providers/processors, serialization groups, filters, and pagination. Use when the task mentions API Platform, ApiResource, state processor, or exposing an entity as a REST/GraphQL endpoint.
/bundle-organizationUse when structuring a Symfony project's src/ directory, organizing code into modules, configuring services, or deciding where a class belongs. Covers the modular monolith layout, service configuration, and config/ conventions for Symfony 7 (Flex, no app bundle).
/console-commandsUse when creating or refactoring Symfony console commands — never extends Command. On Symfony 8.1+ put #[AsCommand] on a method of a service class (even for a single command); on 7.x use the invokable attribute class. Also covers typed CLI inputs via value resolvers and #[MapInput] DTOs. Use when the task mentions console command, #[AsCommand], bin/console, #[Argument], #[Option], or a CLI task.
/doctrine-migrationsUse when changing the database schema in Symfony — generating Doctrine migrations, writing reversible up()/down(), data migrations, and deploy-safe (zero-downtime) changes. Use when the task mentions migration, schema change, ALTER TABLE, or doctrine:migrations.
/doctrine-ormUse when creating Doctrine ORM 3 entities, associations, repositories, enums, or UUID identifiers in Symfony. Defines entity conventions, attribute mapping, fetch strategy, and repository structure. Use when the task mentions entity, Doctrine, repository, association, or mapping.
/domain-driven-designUse when modeling a domain in Symfony — aggregates, entities, value objects, domain events, repositories, and the ubiquitous language. Use when the task mentions DDD, aggregate, value object, domain event, or invariant.
Other plugins' skills for the same job