Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

## 1.1.1 under development

- Enh #590, #594: Add `LazyLoadGuardTrait` and `LazyLoadGuard` to detect N+1 queries
(@KalimeroMK)
- Enh #590, #594, #596: Add `LazyLoadGuardTrait` and `LazyLoadGuard` to detect N+1 queries (@KalimeroMK)

## 1.1.0 May 14, 2026

Expand Down
3 changes: 2 additions & 1 deletion src/ActiveQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,8 @@ public function populate(array $rows): array

$models = $this->createModels($rows);

if (count($models) > 1) {
if (!$this->asArray && count($models) > 1) {
/** @var ActiveRecordInterface[] $models */
LazyLoadGuard::registerResultSet($models);
}

Expand Down
14 changes: 6 additions & 8 deletions src/LazyLoadGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static function set(LazyLoadGuardMode $mode, ?LoggerInterface $logger = n
* the same result set, which is an N+1 query, from the same relation loaded by records that were each
* fetched by a query of their own, which has nothing to eager load across.
*
* @param ActiveRecordInterface[]|array[] $models The models populated from one result set.
* @param ActiveRecordInterface[] $models The models populated from one result set.
*
* @see ActiveQuery::populate()
*/
Expand All @@ -64,7 +64,7 @@ public static function registerResultSet(array $models): void
$resultSet = null;

foreach ($models as $model) {
if (!$model instanceof ActiveRecordInterface || !self::isGuarded($model::class)) {
if (!self::isGuarded($model::class)) {
continue;
}

Expand All @@ -89,12 +89,10 @@ public static function check(ActiveRecordInterface $model, string $relationName)

$resultSets = self::resultSets();

/**
* A record populated outside a result set is a result set of its own.
*
* @psalm-suppress PossiblyNullArgument
*/
$resultSets[$model] ??= new LazyLoadResultSet();
// A record fetched by a query of its own has nothing to eager load across.
if (!isset($resultSets[$model])) {
return;
}

/** @psalm-var LazyLoadResultSet $resultSet */
$resultSet = $resultSets[$model];
Expand Down
Loading