Skip to content

Feature/default loads through relationships - #16

Open
tabennett wants to merge 20 commits into
masterfrom
feature/default-loads-through-relationships
Open

tabennett wants to merge 20 commits into
masterfrom
feature/default-loads-through-relationships

Conversation

@tabennett

@tabennett tabennett commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Eager loads now include the default loads ($with) of related mappers, loads that share a parent merge into one node whatever order they're given in, and withoutDefaultLoads() skips the defaults for a single query.

Closes #15.

What was wrong

  1. A mapper's $with only applied when that mapper was queried directly. Reached through a relationship it was ignored, because every relationship loads raw rows with toBase()->get(), which discards the related builder and its loads.
  2. with('pups.collar')->with('pups') dropped collar, but the reverse order kept it: the bare-name branch of Tree::buildTree() replaced a node a dotted load had already built. A mapper's default 'pups.collar' was lost the same way when a caller added a bare 'pups'.
  3. The rest of a dotted path was found with str_replace("$nodeName.", '', $name), which removes every occurrence and also matches inside other names, so pups.pack.pups.collar became pack.collar and threw UknownRelationshipException.
  4. with() and without() inside a relationship's constraint closure silently did nothing, and constraints given to a custom relationship were silently dropped.

What changed

  • Tree::buildTree() (still iterative, same stack and frame idiom) splits each load once and merges it into the node if it exists. Constraints go on the last segment only, and a node that is just passed through has null constraints.
  • Related defaults. When a new node is created, the related mapper's getWith() is added beneath it. Loads that were asked for always win over defaults, in either order. Custom relationships don't get defaults, since they load with their own query.
  • Loops. The mappers on the path from the root are tracked, and a default that would lead back to one of them is not added. There's no exception, and loads you ask for are never cut off.
  • withoutDefaultLoads() on the builder, in the style of withoutGlobalScopes(). It skips every default load: the queried mapper's own $with and those of related mappers. Loads you ask for still load, whichever order you call it in. Mapper::newQueryWithoutScopes() now hands $with to Tree::addDefaultLoads() so defaults can be told apart from loads that were asked for. getLoads() still lists the mapper's own defaults until you call withoutDefaultLoads().
  • Guard. The hasOne, hasMany, belongsTo and belongsToMany loaders mark the builder they hand to a constraint closure. with(), without() and withoutDefaultLoads() throw a BadMethodCallException there, pointing at the outer query.
  • Custom relationships. The constraints are passed to the load closure as an optional third argument, and you apply them where they belong. Two-argument closures are unaffected.

loadData() and mapData() are unchanged: still one walk of the finished tree each, no extra pass and no new recursion. Entities are hydrated exactly as before.

Behavior changes (read before releasing)

  • A related mapper with a non-empty $with now loads those relations when it's reached through a relationship: more queries, one per relationship, and larger entities.
  • Mappers whose defaults lead to each other (e.g. Pup defaults to collar, Collar defaults to pup) load the way they did before: the queried mapper's own $with one level deep, with the default that leads back skipped.
  • A bare load after a dotted one no longer drops the nested loads. Code that relied on that to prune nested loads will now load more. without('pups.collar') removes an explicit dotted load.
  • with(), without() and withoutDefaultLoads() inside a constraint closure now throw, where they used to do nothing.
  • The defaults of a related mapper can't be removed one at a time with without(), because they aren't in the query's own list of loads. Use withoutDefaultLoads() for the query.
  • Builder gains a public forRelationLoad(), the marker the loaders use. newQueryWithoutScopes() no longer calls with() for the defaults, so a Builder subclass that overrides with() won't see them pass through it.

Worth searching your apps for before upgrading: related mappers with a $with, with() or without() inside constraint closures, and constraints on custom relationships (which now reach the third argument of the load closure).

Docs

  • New page, docs/references/query-builder-api.md: how a query runs, what works and what throws in a constraint closure, the select() contract, default loads and custom relationship constraints.
  • A "Default Loads" section in the relationships overview.
  • Fixed examples that contradicted it: the nested constraints example called with() inside a constraint closure, two limit() examples implied a per-parent limit, and the profile select() example left out the primary key. custom.md also called raw records "entities".

Tests

  • EagerLoadMergeTest, DefaultLoadsTest and RelationConstraintsTest, with small fixture mappers for the mutual, self-referential and constrained cases.
  • 190 tests, 488 assertions. CI is green, 24 of 24.

@tabennett
tabennett force-pushed the feature/default-loads-through-relationships branch 2 times, most recently from b1dfb75 to 3a3eec8 Compare November 15, 2026 07:50
- Add phpstan/phpstan ^2.2 to require-dev and autoload the
  CodeSleeve\Holloway\PhpStan\Extension namespace
- Register dynamic return type extensions so getMapper(), find(),
  get(), paginate(), and where() resolve to concrete entity and
  builder types without annotations on consumer mappers
- Add level 5 phpstan.neon covering src/ and the extension, with
  targeted ignores for SoftDeletes, legacy factories, and helpers
- Add @template TEntity and @method forward declarations so fluent
  query chains preserve the entity type
- Annotate entity, builder, and mapper methods for PHPStan level 5
- Type the $onDelete property and the Holloway singleton, and make
  nullable where()/orWhere() operators explicit
- Replace try/catch with array_key_exists in Holloway::getMapper()
- Read eager loads from the query tree in Builder::getLoads()
- Return void from customMany()/customOne() and drop makeEntity(): mixed
- Resolve getMapper() types from class constants, entity instances,
  and class-strings, including unions of entities
- Type additional forwarded methods: all, makeEntity, makeEntities,
  instantiateEntity, newCollection, newQueryWithoutScopes,
  newQueryWithoutScope, and newHollowayBuilder
- Return the union of collection and nullable entity from find()
  when the argument type cannot be narrowed
- Align Builder and Mapper @method signatures with the argument
  types Illuminate accepts (Expression, Closure, iterable, mixed)
- Assert entity, collection, paginator, and builder return types
  through TypeInferenceTestCase
- Cover getMapper() lookups by class constant, entity instance, and
  class-string, including a union of entity classes
- Add a level 8 config over the fixtures so forwarded argument
  types are validated, not just inferred return types
- Run PHPStan over src/ and the extension on PHP 8.3
- Run the level 8 fixture config to catch argument-type drift in
  forwarded @method signatures
- Install from the lock file for reproducible builds
- Add a static analysis guide covering installation, inferred types,
  registry lookups, level 6+ generics, and limitations
- Link it from the readme
- Declare extra.phpstan.includes so phpstan/extension-installer
  auto-registers the extension
- Accept anything Laravel accepts for where()/orWhere() and the pass-through
  query methods: untype the Builder::where()/orWhere() operator (it is no
  longer coerced to a string) and use variadic mixed arguments in the
  @method tags.
- Give Mapper and Builder a default template type so raw Mapper/Builder
  references (extends Mapper, a Builder parameter in a scope) don't raise
  missingType.generics.
- Return the concrete paginator classes, and drop the class-string
  annotation on getEntityClassName(), which conflicted with plain string
  implementations.
- Don't replace the return types of methods that a mapper overrides, such as
  find() or get().
- Add an overriding mapper fixture and type-inference tests for the above.
- State that no @extends annotation is needed at any level.
- Note that level 8 reports nullable find()/first() results.
- Document that scopes and soft-delete macros must be declared with @method,
  and that overridden mapper methods keep their own return types.
- Resolve scopeXxx() methods as xxx() on a concrete mapper and anywhere in a
  query chain from it, with the scope's own parameters (minus $query) checked.
  Resolve withTrashed(), withoutTrashed() and onlyTrashed() on mappers that
  use SoftDeletes.
- Give Builder a second template type, Builder<TEntity, TMapper>, which the
  extension sets wherever a builder comes from a concrete mapper. Carry it
  through the @method tags and builder return types ($this / static).
- Share the mapper-to-entity lookup between the extensions in a new
  EntityTypeResolver.
- Fall back to the @method tags for a union of mappers instead of resolving
  only the first mapper's entity.
- Ignore PHPStan's backward compatibility notice for the method reflection
  class in the project's own analysis.
- Add scope, macro and union type-inference tests and update the builder
  type expectations.
- Add a section on scopes and soft-delete macros, including what is not
  resolved (mappers from Holloway::getMapper(), bare Builder parameters).
- Note that the extension targets PHPStan 2.x.
get() takes no arguments, so get(['id', 'name']) selects every column. Point
to select() for limiting columns.
…dReflection

PHPStan 2.3 added the abstract method getPureUnlessParameterPassedParameters()
to ExtendedMethodReflection. ScopeMethodReflection implements that interface,
so with a fresh install the class failed to load with a fatal error as soon as
the type inference tests were discovered, and every job that runs the test
suite exited with 255. The interface isn't covered by PHPStan's backward
compatibility promise, which is why a minor release could add it.

Return an empty array, since nothing is known about the purity of a scope or a
soft-delete macro, the way PHPStan's own dummy reflection does. The method is
simply extra on the 2.2 interface, so older installs are unaffected.
A mapper's $with was only applied to queries run directly on that mapper.
Reached through a relationship it was ignored, because relationships load
raw rows with toBase()->get() and the related Builder's loads were thrown
away along with it.

Tree::buildTree() now adds the default loads of the mapper that a new node
leads to as children of that node. It does this on the same stack it already
builds loads with, so loadData() and mapData() are untouched and each still
walks the finished tree once.

- Loads that were asked for win over defaults, in either order. A default
  only fills in what's missing.
- A node that was only passed through on the way to a nested load has null
  constraints until a load or a default gives it some, so a default's
  constraints still apply to it whatever order the loads are given in.
  Loaders already treat null constraints as a no-op.
- Default loads are not added beneath custom relationships, which load their
  records with their own query.
- The mappers whose defaults led to a load are tracked along each path. If a
  mapper turns up in its own chain its defaults lead back around to
  themselves, and a CircularDefaultLoadsException naming the chain is thrown
  instead of expanding forever.

Building the tree this way also fixes two bugs in how loads were merged:

- A bare load given after a dotted one, with('pups.collar')->with('pups'),
  replaced the node the dotted load had built and dropped its children.
  Loads are now merged by node, so the order they're given in no longer
  matters (this also keeps a mapper's default 'pups.collar' when a caller
  adds a bare 'pups').
- The rest of a dotted path was found with str_replace(), which removes
  every occurrence of the prefix and matches inside other names, so
  'pups.pack.pups.collar' became 'pack.collar'. It is now split once.

Behavior change: a related mapper with a non-empty $with now loads those
relationships when it's reached through a relationship, which means more
queries (one per relationship). Mappers whose defaults point at each other
now throw instead of silently ignoring the related defaults.

Add tests for merging loads in either order and for default loads through
hasMany and belongsTo, cascading and nested defaults, constraints, custom
relationships, getLoads(), and both cycle cases, with small fixture mappers
that declare a $with.
Describe that a mapper's $with is also loaded when the mapper is reached
through a relationship, that loads asked for win over defaults, that custom
relationships don't get them, that defaults leading back around to themselves
throw a CircularDefaultLoadsException, and that without() can't remove the
default loads of a related mapper.
…e::buildTree

Rename the variables in buildTree() so they read as what they hold
($mapperChain, $relatedMapper, $remainingPath, $isNewNode, $isDefaultLoad,
$defaultName), and describe the method as numbered steps in the body, the way
the rest of the class is written. Shorten the docblock to two sentences.

No change in behavior.
…e path

Adding the default loads of related mappers threw a
CircularDefaultLoadsException when a mapper's defaults led back to a mapper
that was already being loaded. A pup that defaults to its collar with a
collar that defaults to its pup, or a mapper whose default is a relationship
to itself, would throw on every query, where it loaded fine before related
defaults were added.

Keep the mappers on the path from the root to the node being built, starting
with the root mapper, and don't add a default load that leads to one of
them. Loads that were asked for are never cut off, and the root mapper's own
$with still loads one level as it always has. The exception and its helper
are removed.

Add tests for a pair of mappers whose defaults lead to each other (from
either side), a default that leads back to its own mapper, and a path that
was asked for coming back around to a mapper, with fixture mappers for the
mutual and self-referential cases. Change the belongsTo test to a path that
doesn't loop and update the docs.
…r a query

Default loads now load whenever a mapper is reached through a relationship,
and without() can't remove them because they aren't in the query's own
loads. Add withoutDefaultLoads() on the builder, in the same style as
withoutGlobalScopes(), to skip every default load for a single query: the
$with of the mapper being queried and of the mappers it leads to. Loads that
were asked for still load, whichever order they're asked for in.

Tree keeps track of which loads came from the root mapper's $with so they can
be told apart from loads that were asked for, and Mapper hands its $with to
Tree::addDefaultLoads() instead of with().

Add tests and document it.
…onstraints

A constraint closure is handed the query that loads a relationship, but only
the rows it returns are used: the loads of a query are decided by the tree
before any query runs. Calling with(), without() or withoutDefaultLoads() in
one silently did nothing.

Mark the query that the standard relationships (hasOne, hasMany, belongsTo and
belongsToMany) hand to their constraints, and have those three methods throw
a BadMethodCallException that points at the outer query instead.

Pass the constraints of a custom relationship to its load closure as an
optional third argument, so they can be applied to the query the closure
builds. Closures that take two arguments are unaffected and ignore them.

Add tests for each relationship type and method, for the constraints that are
still allowed, and for the custom relationship constraints.
Add a page covering what works, what differs and what throws in a mapper's
query API: the three steps a query runs in, constraint closures, select(),
default loads and custom relationship constraints.

Fix the examples that contradicted it. The nested constraints example called
with() inside a constraint closure, which never worked. The limit() examples
implied a per-parent limit, and the profile select() example left out the
primary key. Describe the arguments of a custom relationship's load and for
functions as records, and document the constraints argument.
@tabennett
tabennett force-pushed the feature/default-loads-through-relationships branch from 3a3eec8 to 7272eda Compare November 15, 2026 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Eager loads: a bare parent load after a dotted load drops the nested loads (order-dependent)

1 participant