diff --git a/CHANGELOG.md b/CHANGELOG.md index be71dadca55..f9d225e9f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Release Notes for Craft CMS 5 +## Unreleased + +- Fixed an error that could occur when eager-loading nested elements’ owners, if any of the queried elements didn’t have an owner ID. ([#16570](https://github.com/craftcms/cms/issues/16570), [#16572](https://github.com/craftcms/cms/issues/16572), [#16576](https://github.com/craftcms/cms/issues/16576)) + ## 5.6.2 - 2024-01-28 - The Login page now displays the Login Page Logo above the login form, rather than within the header. ([#16564](https://github.com/craftcms/cms/pull/16564)) diff --git a/src/base/NestedElementTrait.php b/src/base/NestedElementTrait.php index 7078bccdf68..3d102c36177 100644 --- a/src/base/NestedElementTrait.php +++ b/src/base/NestedElementTrait.php @@ -45,13 +45,16 @@ public static function eagerLoadingMap(array $sourceElements, string $handle): a return [ 'elementType' => $ownerType, - 'map' => array_map(fn(NestedElementInterface $element) => [ - 'source' => $element->id, - 'target' => match ($handle) { + 'map' => array_filter(array_map(function(NestedElementInterface $element) use ($handle) { + $ownerId = match ($handle) { 'owner' => $element->getOwnerId(), 'primaryOwner' => $element->getPrimaryOwnerId(), - }, - ], $sourceElements), + }; + return $ownerId ? [ + 'source' => $element->id, + 'target' => $ownerId, + ] : null; + }, $sourceElements)), 'criteria' => [ 'status' => null, ], diff --git a/src/services/Elements.php b/src/services/Elements.php index 52be3087f06..0be9dafa650 100644 --- a/src/services/Elements.php +++ b/src/services/Elements.php @@ -3235,8 +3235,10 @@ private function _eagerLoadElementsInternal(string $elementType, array $elements $targetElementIdsBySourceIds = []; foreach ($map['map'] as $mapping) { - $uniqueTargetElementIds[$mapping['target']] = true; - $targetElementIdsBySourceIds[$mapping['source']][$mapping['target']] = true; + if (!empty($mapping['target'])) { + $uniqueTargetElementIds[$mapping['target']] = true; + $targetElementIdsBySourceIds[$mapping['source']][$mapping['target']] = true; + } } // Get the target elements