agentleFS
AnyOrgNameAnyOrgName/php-skills/skills/doctrine/associations/SKILL.md

associations

Skill4 starsChanged 4 months agoMITView on GitHub

Model relationships between Doctrine entities — OneToMany, ManyToOne, and ManyToMany, the owning versus inverse side, fetch modes, and avoiding the N+1 query problem. Use when the user sees many repeated queries when iterating a Doctrine collection and needs to fix the N+1 problem; the user must decide which side of a bidirectional Doctrine association owns the relationship and holds the foreign key; the user needs to model a relationship between Doctrine entities — one-to-many, many-to-one, or many-to-many. Keywords: doctrine, orm, associations, relationships, owning-side, fetch, n+1, performance.

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not create a direct ORM association across a bounded-context or aggregate boundary that should be referenced by id only.

    line 64
  2. Distinctive:

    Do not map an association when one entity only needs another's identifier value, not a navigable object graph.

    line 65
  3. Very specific:

    Use a plain #[ORM\ManyToMany] only when the link is a pure set membership

    line 96
  4. Distinctive:

    Not applicable — no I/O, auth, or untrusted input.

    line 125

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- generated: do not edit — source: knowledge/atoms/doctrine/associations/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->

Doctrine Associations

When to use

  • The user sees many repeated queries when iterating a Doctrine collection and needs to fix the N+1 problem.
  • The user must decide which side of a bidirectional Doctrine association owns the relationship and holds the foreign key.
  • The user needs to model a relationship between Doctrine entities — one-to-many, many-to-one, or many-to-many.

When NOT to use

  • Do not create a direct ORM association across a bounded-context or aggregate boundary that should be referenced by id only.
  • Do not map an association when one entity only needs another's identifier value, not a navigable object graph.

Core guidance

  • Bound and paginate fetch-joined to-many collections — When fetch-joining a to-many association, paginate with the Doctrine Paginator rather than a raw LIMIT, and avoid joining several unbounded to-many collections in one query.
  • Keep associations lazy and fetch-join per query — Leave associations at the default LAZY fetch mode and pull related data on demand with an explicit fetch join (->leftJoin(...)->addSelect(...)) in the queries that need it, rather than mapping the association as EAGER.
  • The owning side holds the foreign key and drives persistence — Put the owning side on the entity that holds the foreign-key column — the ManyToOne side of a one-to-many, or the side with inversedBy. Doctrine only reads changes from the owning side, and the inverse side uses mappedBy.

Quick recipe

  1. On the child entity, map the owning side with #[ORM\ManyToOne(inversedBy: 'items')] #[ORM\JoinColumn(nullable: false)] so it holds the foreign key back to the parent. (verify: The child table's migration includes the parent foreign-key column.)
  2. On the parent, map the inverse side with #[ORM\OneToMany(mappedBy: 'order', targetEntity: Item::class)], initialize the collection to new ArrayCollection(), and add addItem()/removeItem() that keep both sides in sync. (verify: Adding an item through the helper sets the item's parent reference and appears in the collection.)
  3. In the list query that displays parents with their children, add ->leftJoin('o.items', 'i')->addSelect('i') so the whole graph loads in one query instead of N+1 lazy loads. (verify: A SQL log of the list endpoint shows a single joined query, not one query per parent.)

Best practices

  • Apply cascade: ['persist', 'remove'] (or orphanRemoval) only when the related entities are owned parts of the same aggregate, such as order line items
  • Use a plain #[ORM\ManyToMany] only when the link is a pure set membership
  • For a bidirectional association, update both sides inside a helper method (for example Order::addItem() that sets $item->setOrder($this) and adds to the collection) so the in-memory object graph stays consistent

Anti-patterns

Anti-patternWhy it failsDo instead
Typing a to-many association as a plain arrayDoctrine hydrates to-many sides as a Collection (PersistentCollection); a plain array breaks lazy loading and change tracking on the relation.Initialize the property to a new ArrayCollection() in the constructor and type it as Collection.
Blanket cascade including refresh and detachcascade all includes refresh and detach, propagating operations across the graph in ways that trigger extra queries and unexpected state resets.List only the cascades the aggregate needs, typically just persist and remove within the aggregate root.
Marking associations EAGER to avoid thinking about fetchingEAGER pulls the related graph on every query of the parent, so unrelated read paths pay for joins and hydration they never use.Keep the mapping LAZY and add a targeted fetch join in the specific queries that traverse the association.

See references/anti-patterns.md.

Common mistakes

  1. Counting a lazy collection hydrates every element — Calling count($order->getItems()) on a lazy collection can hydrate all items just to count them. Fix: Use the collection's ->count() on an uninitialized PersistentCollection (which issues a COUNT), or a dedicated repository count query.
  2. Iterating a lazy collection fires one query per row — Looping over parents and touching a lazy association inside the loop issues one extra query per parent — the N+1 problem. Fix: Fetch-join the association in the list query (->leftJoin('o.customer', 'c')->addSelect('c')), or enable Doctrine batch fetching for the association.
  3. Updating only the inverse side saves nothing — Adding to the inverse-side collection without setting the owning side leaves the foreign key unwritten on flush. Fix: Set the owning side (the ManyToOne reference) in the sync helper; the inverse collection is for reads and in-memory consistency.

Version notes

  • ORM 3 uses native lazy objects where available (PHP >=8.1) — Doctrine ORM 3 generates lazy proxies with less reliance on the proxy generator, using PHP native lazy objects on supported runtimes; behavior of lazy loading is unchanged for application code.

Security

  • Not applicable — no I/O, auth, or untrusted input.

Testing

  • Activation and decision behavior are verified in eval/scenarios/doctrine/associations.yaml.

Additional resources

  • references/anti-patterns.md
  • references/core.md
  • references/examples.md
  • references/pitfalls.md
  • references/recipes.md
  • references/version-differences.md

Knowledge graph

Related: doctrine/entities-mapping, doctrine/orm-basics, laravel/eloquent-relationships

<!-- graph-fragment: graph/fragments/doctrine/associations.yaml -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.