Skip to content

Allow has method with numeric indexes #2187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/Helpers/QueriesRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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));
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/RelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down