Skip to content

Commit c1b4747

Browse files
Optimizing int related id handling
1 parent e362198 commit c1b4747

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

Diff for: src/Jenssegers/Mongodb/Helpers/QueriesRelationships.php

+8-1
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,10 @@ protected function getHasCompareKey(Relation $relation)
123123
protected function getConstrainedRelatedIds($relations, $operator, $count)
124124
{
125125
$intHash = 'INT_RELATION_';
126-
$relationCount = array_count_values(array_map(function ($id) use ($intHash) {
126+
$hasNumericIndex = false;
127+
$relationCount = array_count_values(array_map(function ($id) use ($intHash, &$hasNumericIndex) {
127128
if (!is_string($id) && is_int($id)) {
129+
$hasNumericIndex = true;
128130
return $intHash . $id;
129131
}
130132
return (string) $id; // Convert Back ObjectIds to Strings
@@ -149,6 +151,11 @@ protected function getConstrainedRelatedIds($relations, $operator, $count)
149151
});
150152

151153
// All related ids.
154+
if(!$hasNumericIndex) {
155+
return array_keys($relationCount);
156+
}
157+
158+
// Has any numeric index?
152159
return array_map(static function ($id) use ($intHash) {
153160
if (strpos($id, $intHash, 0) === 0) {
154161
return (int) str_replace($intHash, '', $id);

Diff for: tests/RelationsTest.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -438,10 +438,13 @@ public function testHasManyHas(): void
438438

439439
public function testHasNumeric(): void
440440
{
441-
$author1 = User::create(['_id' => '1', 'name' => 'George R. R. Martin']);
442-
$author1->books()->create(['_id' => '1', 'title' => 'A Game of Thrones', 'rating' => 5]);
441+
$author1 = User::create(['name' => 'George R. R. Martin']);
442+
$author1->books()->create(['title' => 'A Game of Thrones', 'rating' => 5]);
443443
$author1->books()->create(['_id' => '2', 'title' => 'A Clash of Kings', 'rating' => 5]);
444444

445+
$author2 = User::create(['name' => 'John Doe']);
446+
$author2->books()->create(['title' => 'My book', 'rating' => 2]);
447+
445448
$authors = User::has('books', '>', 1)->get();
446449
$this->assertCount(1, $authors);
447450
}

0 commit comments

Comments
 (0)