diff --git a/src/ORM/EagerLoadedList.php b/src/ORM/EagerLoadedList.php index 8a53c88905d..887953538b8 100644 --- a/src/ORM/EagerLoadedList.php +++ b/src/ORM/EagerLoadedList.php @@ -485,28 +485,40 @@ public function find($key, $value): ?DataObject public function filter(...$args): static { - $filters = $this->normaliseFilterArgs($args, __FUNCTION__); $list = clone $this; - $list->rows = $this->getMatches($filters); + + if ($list->rows) { + $filters = $list->normaliseFilterArgs($args, __FUNCTION__); + $list->rows = $this->getMatches($filters); + } + return $list; } public function filterAny(...$args): static { - $filters = $this->normaliseFilterArgs($args, __FUNCTION__); $list = clone $this; - $list->rows = $this->getMatches($filters, true); + + if ($list->rows) { + $filters = $list->normaliseFilterArgs($args, __FUNCTION__); + $list->rows = $this->getMatches($filters, true); + } + return $list; } public function exclude(...$args): static { - $filters = $this->normaliseFilterArgs($args, __FUNCTION__); - $toRemove = $this->getMatches($filters); $list = clone $this; - foreach ($toRemove as $id => $row) { - unset($list->rows[$id]); + + if ($list->rows) { + $filters = $list->normaliseFilterArgs($args, __FUNCTION__); + $toRemove = $list->getMatches($filters); + foreach ($toRemove as $id => $row) { + unset($list->rows[$id]); + } } + return $list; } @@ -517,12 +529,16 @@ public function exclude(...$args): static */ public function excludeAny(...$args): static { - $filters = $this->normaliseFilterArgs($args, __FUNCTION__); - $toRemove = $this->getMatches($filters, true); $list = clone $this; - foreach ($toRemove as $id => $row) { - unset($list->rows[$id]); + + if ($list->rows) { + $filters = $list->normaliseFilterArgs($args, __FUNCTION__); + $toRemove = $list->getMatches($filters, true); + foreach ($toRemove as $id => $row) { + unset($list->rows[$id]); + } } + return $list; } diff --git a/tests/php/ORM/EagerLoadedListTest.php b/tests/php/ORM/EagerLoadedListTest.php index 901502acd2a..5b2f07d195c 100644 --- a/tests/php/ORM/EagerLoadedListTest.php +++ b/tests/php/ORM/EagerLoadedListTest.php @@ -2345,4 +2345,21 @@ public function testDebug() ); $this->assertStringEndsWith('', $result); } + + public function testEmptyList() + { + $list = Category::get()->eagerLoad('Products'); + $categoryA = $this->idFromFixture(Category::class, 'categorya'); + + /** @var Category $category */ + foreach ($list as $category) { + $count = $category->Products()->filter('Title:StartsWith', 'Product')->count(); + + if ($category->ID == $categoryA) { + $this->assertEquals(2, $count); + } else { + $this->assertEquals(0, $count); + } + } + } }