Skip to content

Pick of-many rows with a grouped max or min join - #614

Merged
taylorotwell merged 2 commits into
0.xfrom
of-many-grouped
Dec 2, 2026
Merged

taylorotwell merged 2 commits into
0.xfrom
of-many-grouped

Conversation

@taylorotwell

Copy link
Copy Markdown
Member

Fixes #534. Supersedes #546, whose commit this keeps.

Eager loading a latest_of_many, oldest_of_many, or of_many relation kept each related row whose key equals a subquery correlated with that row. MySQL runs that subquery once for every related row the outer in matches, so a load read (related rows) × (related rows per parent): about 80 seconds for 40 parents with 2,000 rows each. has, where_has, exists_where, count, and count_where used the same correlated pick.

Change

Every of_many path now picks the way Eloquent's ofMany does. A grouped subquery finds each parent's largest or smallest value of the column, and the related rows join it. row_number() then breaks ties by key among the few rows left:

and `deployments`.`id` in (
  select `laravel_ranked`.`id` from (
    select `r`.`id`, row_number() over (partition by `r`.`environment_id` order by `r`.`size` desc, `r`.`id` desc) as `laravel_row`
    from `deployments` as `r`
    inner join (
      select `g`.`environment_id` as `laravel_partition`, max(`g`.`size`) as `laravel_extreme`
      from `deployments` as `g` where `g`.`environment_id` in (...) group by `g`.`environment_id`
    ) as `e` on `e`.`laravel_partition` = `r`.`environment_id` and `e`.`laravel_extreme` = `r`.`size`
  ) as `laravel_ranked` where `laravel_ranked`.`laravel_row` = 1)

The subquery never refers to the outer row, so a database runs it once per query. Loading, aggregates, and the relation query from one parent pass the parents' keys into the grouped subquery. has and count leave the keys out, as Eloquent does. NULL skipping, the key tie-break, conditions that apply after the pick, and through, morph, filtered, and self relations behave as before.

PostgreSQL has no max for uuid. The new ModelKey::AGGREGATES constant is true by default and false for Uuid and newtypes over it. For those keys, a relation that picks by key ranks all of a parent's rows instead of grouping.

Numbers

MySQL 8.4, 40 parents × 1,000 rows, index on (environment_id, size), the SQL the framework emits, 3 runs each:

Query 0.x #546 This PR
Eager of_many(size, max) ~5.9 s 22–25 ms 2.3–2.6 ms
has(of_many(size, max)) 7.6 s 7.6 s 1.4–1.9 ms
of_many(size, max).count().ge(1) correlated correlated 4.5–4.7 ms

Eloquent's SQL for the same eager load and has took 1.7–2.1 ms and 1.1 ms on the same data.

Tests

  • of_many_picks_among_the_parents_rows_at_once (from Pick of-many rows with one ranked subquery when loading #546) checks loading, with_count, and the relation query pick with one ranked query.
  • of_many_picks_by_uuid_keys_and_in_self_relations covers a Uuid-keyed latest_of_many and of_many(max) with a tie, through with, has_where, and count, and has / has_where on a self-relation. With Uuid's AGGREGATES set to true, it fails on PostgreSQL with function max(uuid) does not exist.

The model_ tests pass on SQLite, MySQL, and PostgreSQL.

benodeveloper and others added 2 commits December 2, 2026 22:32
Eager loading a latest_of_many relation kept the row whose key equals a
subquery correlated with each related row. MySQL runs that subquery once
for every related row, so the load read (related rows) x (related rows
per parent): 57 seconds for 40 parents with 2,000 rows each.

Loading, counting and lazily querying the relation now number the rows
of the parents being loaded with row_number(), once, and keep each
parent's first. has() and where_has() still correlate with the parent
table, as they did.

Refs #534

Co-authored-by: Taylor Otwell <taylor@laravel.com>
Every of_many path now picks the way Eloquent does: a grouped subquery
finds each parent's largest or smallest value of the column, the related
rows join it, and row_number() breaks ties by key among the rows left.
The subquery never refers to the outer row, so it runs once per query.

This replaces both the ranked pick that loading used and the correlated
pick that has(), where_has(), exists_where(), count(), and count_where()
still used. On MySQL with 40 parents and 1,000 rows each, has() on an
of_many relation drops from 7.6 s to under 2 ms, and eager loading from
about 24 ms to about 2.5 ms.

PostgreSQL has no max() for uuid, so ModelKey::AGGREGATES lets a Uuid
key, and a newtype over one, rank every related row when picking by key.

Amp-Thread-ID: https://ampcode.com/threads/T-b3ca1dbf-3c50-4286-a702-945a9f477ede
Co-authored-by: Taylor Otwell <taylor@laravel.com>
@taylorotwell
taylorotwell merged commit 4e35870 into 0.x Dec 2, 2026
17 of 18 checks passed
@taylorotwell
taylorotwell deleted the of-many-grouped branch December 2, 2026 23:04
@taylorotwell taylorotwell added bug p1 Priority 1: highest, fix first labels Dec 2, 2026 — with Amp for GitHub

Copy link
Copy Markdown
Member Author

This is an automated, agent-powered review. The bug is confirmed. On MySQL with 40 environments and 1,000 deployments each, indexed on (environment_id, size), 0.x takes about 8 seconds to eager load, filter with has, or count an of_many(size, max) relation, and about 144 seconds to eager load or filter with has on a latest_of_many relation, because every pick runs a subquery correlated with each related row. On this branch the same queries take 5 to 32 ms. of_many_picks_among_the_parents_rows_at_once fails on 0.x on SQLite, PostgreSQL, and MySQL. After merging into the current 0.x, the model tests in the database suite pass on all three. The grouped join replaces the correlated subquery in picked, where the slow query was built, so I left the change as it is.

Two things to look at in the human review. ModelKey::AGGREGATES is a new public associated constant; it defaults to true, so existing key types still compile, but a hand-written ModelKey over a PostgreSQL uuid column has to set it to false. Also, max and min now run on the of_many column itself, so on PostgreSQL a relation that picks by a uuid or boolean column, which ordering used to handle, now fails with function max(boolean) does not exist. That is a narrow case, but the guide could say which column types of_many accepts. Thanks for your contribution, a human review will follow shortly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug p1 Priority 1: highest, fix first

Projects

None yet

Development

Successfully merging this pull request may close these issues.

#[has_one(latest_of_many = ...)] eager load runs a correlated subquery once per related row on MySQL

3 participants