diff -u b/core/lib/Drupal/Core/Entity/EntityStorageBase.php b/core/lib/Drupal/Core/Entity/EntityStorageBase.php --- b/core/lib/Drupal/Core/Entity/EntityStorageBase.php +++ b/core/lib/Drupal/Core/Entity/EntityStorageBase.php @@ -364,8 +364,12 @@ $entities_by_class = $this->getEntitiesByClass($entities); // Invoke entity class specific postLoad() methods. - foreach ($entities_by_class as $entity_class => &$items) { - $entity_class::postLoad($this, $items); + foreach (array_keys($entities_by_class) as $entity_class) { + // We must pass the full $entities array each time, so that if a + // postLoad() method is trying to reorder the array (for example, + // \Drupal\user\Entity\Role::postLoad()), it can actually manipulate the + // final array, not a subarray. + $entity_class::postLoad($this, $entities); } // Call hook_entity_load(). foreach ($this->moduleHandler()->getImplementations('entity_load') as $module) { diff -u b/core/tests/Drupal/KernelTests/Core/Entity/BundleClassTest.php b/core/tests/Drupal/KernelTests/Core/Entity/BundleClassTest.php --- b/core/tests/Drupal/KernelTests/Core/Entity/BundleClassTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/BundleClassTest.php @@ -146,11 +146,11 @@ $this->assertEquals(2, EntityTestBundleClass::$postLoadCount); $this->assertCount(2, EntityTestBundleClass::$postLoadEntitiesCount); - // Only 3 of the 5 entities we just loaded use the bundle class. However, - // one of them has already been loaded and we're getting the cached entity - // without re-invoking postLoad(). So the custom postLoad() method should - // only have been invoked with 2 entities. - $this->assertEquals(2, EntityTestBundleClass::$postLoadEntitiesCount[1]); + // Only 4 of the 5 requested entities need to be loaded. The other ($entity) + // has already been loaded and we're getting the cached entity without + // re-invoking postLoad(). So the custom postLoad() method should only have + // been invoked with 4 entities. + $this->assertEquals(4, EntityTestBundleClass::$postLoadEntitiesCount[1]); // Reset the storage cache and try loading again. $this->storage->resetCache(); @@ -158,8 +158,8 @@ $entities = $this->storage->loadMultiple($entity_ids); $this->assertEquals(3, EntityTestBundleClass::$postLoadCount); $this->assertCount(3, EntityTestBundleClass::$postLoadEntitiesCount); - // This time, all 3 bundle_class entities should be included. - $this->assertEquals(3, EntityTestBundleClass::$postLoadEntitiesCount[2]); + // This time, all 5 entities should be included. + $this->assertEquals(5, EntityTestBundleClass::$postLoadEntitiesCount[2]); // Start deleting things and count delete-related method invocations. $entity_test_1->delete();