diff --git a/src/Helpers/QueriesRelationships.php b/src/Helpers/QueriesRelationships.php index ee130ce79..acddb0dd4 100644 --- a/src/Helpers/QueriesRelationships.php +++ b/src/Helpers/QueriesRelationships.php @@ -122,7 +122,15 @@ protected function getHasCompareKey(Relation $relation) */ protected function getConstrainedRelatedIds($relations, $operator, $count) { - $relationCount = array_count_values(array_map(function ($id) { + $intHash = 'INT_RELATION_'; + $hasNumericIndex = false; + $relationCount = array_count_values(array_map(function ($id) use ($intHash, &$hasNumericIndex) { + if (! is_string($id) && is_int($id)) { + $hasNumericIndex = true; + + return $intHash.$id; + } + return (string) $id; // Convert Back ObjectIds to Strings }, is_array($relations) ? $relations : $relations->flatten()->toArray())); // Remove unwanted related objects based on the operator and count. @@ -145,7 +153,18 @@ protected function getConstrainedRelatedIds($relations, $operator, $count) }); // All related ids. - return array_keys($relationCount); + if (! $hasNumericIndex) { + return array_keys($relationCount); + } + + // Has any numeric index? + return array_map(static function ($id) use ($intHash) { + if (strpos($id, $intHash, 0) === 0) { + return (int) str_replace($intHash, '', $id); + } + + return (string) $id; + }, array_keys($relationCount)); } /** diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 59d0f2757..5046ef4bc 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -437,6 +437,26 @@ public function testHasManyHas(): void $this->assertCount(1, $authors); } + public function testHasNumeric(): void + { + $author1 = User::create(['_id' => 1, 'name' => 'George R. R. Martin']); + $author1->books()->create(['title' => 'A Game of Thrones', 'rating' => 5]); + $author1->books()->create(['title' => 'A Clash of Kings', 'rating' => 5]); + + // Mixing with int passed as string + $author2 = User::create(['_id' => '2', 'name' => 'John Doe']); + $author2->books()->create(['title' => 'My book', 'rating' => 2]); + + $authors = User::has('books', '>', 1)->get(); + $this->assertCount(1, $authors); + + $authors = User::has('books')->get(); + $this->assertCount(2, $authors); + + $authors = User::has('books', '>', 2)->get(); + $this->assertCount(0, $authors); + } + public function testHasOneHas(): void { $user1 = User::create(['name' => 'John Doe']);