Doctrine Query Optimization logo

Doctrine Query Optimization

Community
fatonh
doctrine-query-optimization

Use when writing Doctrine queries, fixing N+1 problems, paginating large result sets, building read models, or tuning DQL/query builder performance. Use when the task mentions N+1, slow query, pagination, DQL, hydration, or read model.

Overview

Publisherfatonh
Repositorysymfony-skills
Skill namedoctrine-query-optimization
Stars
36
Forks
3
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by fatonh on GitHub. Read the source before you install it.

Installation

Install the Doctrine Query Optimization AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/fatonh/symfony-skills/tree/main/skills/doctrine-query-optimization
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fatonh/symfony-skills.git /tmp/symfony-skills
mkdir -p .claude/skills
cp -r /tmp/symfony-skills/skills/doctrine-query-optimization .claude/skills/doctrine-query-optimization
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Doctrine Query Optimization in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Doctrine Query Optimization on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Doctrine Query Optimization is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Doctrine Query Optimization (Symfony)

N+1: identify and fix

One query for the parents + one query per parent for a lazy association = N+1. It hides in loops that touch a lazy relation.

php
// ❌ 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):

php
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):

php
$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.

php
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
}

Hydration modes

  • Default getResult() returns managed entities — most expensive (UoW tracks them).
  • getArrayResult() / getScalarResult() — when you only read and never mutate.
  • DQL NEW (DTO hydration) — best for read endpoints; immutable, no identity map cost.
  • For read-only list endpoints, prefer DTOs over entities every time.

Pagination

php
// 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.

php
// ✅ 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.

Batch processing large sets

Don't load a million rows into memory. Iterate and clear the identity map periodically.

php
$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).

Other wins

  • Select only the columns you need with partial DTO hydration, not whole entities.
  • Use EXISTS/SELECT 1 … setMaxResults(1) for existence checks, not count() of loaded rows.
  • Add a second-level / result cache only for genuinely hot, rarely-changing queries — measure first.
  • Profile with the Symfony Profiler's Doctrine panel; watch query count and duplicate queries.

Gotchas

  • Agent writes a loop that touches a lazy association — fetch-join it or use a read-model DTO.
  • Agent fetch-joins a to-many and paginates with plain setMaxResults — wrap in Paginator(fetchJoinCollection: true).
  • Agent hydrates full entities for a read-only list endpoint — use DQL NEW DTO hydration.
  • Agent uses OFFSET for deep pagination — switch to keyset/seek on a sortable indexed key.
  • Agent loads huge result sets into an array — use toIterable() + periodic flush()/clear().
  • Agent calls count($repo->findBy(...)) to check existence — use an EXISTS/SELECT 1 query.
  • Agent forgets to index the column used in WHERE/ORDER BY for keyset — add the index.

Frequently asked questions

What does the Doctrine Query Optimization AI skill do?

Use when writing Doctrine queries, fixing N+1 problems, paginating large result sets, building read models, or tuning DQL/query builder performance. Use when the task mentions N+1, slow query, pagination, DQL, hydration, or read model.

Why use Doctrine Query Optimization on TypingMind?

Because you install it once and use it with any model. Doctrine Query Optimization is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Doctrine Query Optimization in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/fatonh/symfony-skills/tree/main/skills/doctrine-query-optimization. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Doctrine Query Optimization?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Doctrine Query Optimization?

As many as you like. As long as a model supports skills, you can use Doctrine Query Optimization with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Doctrine Query Optimization AI skill free?

Yes. It is published on GitHub by fatonh under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇