Skip to content

Commit f100e48

Browse files
authored
PHPLARA-73 Make id/_id column aliasing overridable via Grammar (#3539)
Delegate the top-level `id` to `_id` column rename in `Builder::compileWheres()` to `Grammar::prepareFieldsForQuery()` so users can extend the Grammar to disable the aliasing when documents have a business `id` field alongside `_id`.
1 parent d5e4c31 commit f100e48

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

src/Query/Builder.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
use function array_filter;
3737
use function array_is_list;
3838
use function array_key_exists;
39+
use function array_key_first;
3940
use function array_keys;
4041
use function array_map;
4142
use function array_merge;
@@ -1293,10 +1294,11 @@ protected function compileWheres(): array
12931294
if (isset($where['column'])) {
12941295
$where['column'] = (string) $where['column'];
12951296

1296-
// Compatibility with Eloquent queries that uses "id" instead of MongoDB's _id
1297-
if ($where['column'] === 'id') {
1298-
$where['column'] = '_id';
1299-
}
1297+
// Compatibility with Eloquent queries that use "id" instead of MongoDB's _id.
1298+
// Delegates to Grammar::prepareFieldsForQuery so the aliasing is overridable.
1299+
$where['column'] = (string) array_key_first(
1300+
$this->grammar->prepareFieldsForQuery([$where['column'] => null]),
1301+
);
13001302

13011303
// Convert id's.
13021304
if ($where['column'] === '_id' || str_ends_with($where['column'], '._id')) {

tests/Query/BuilderTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1736,6 +1736,29 @@ public static function provideDisableRenameEmbeddedIdField()
17361736
];
17371737
}
17381738

1739+
public function testCustomGrammarDisablesIdAliasing()
1740+
{
1741+
$connection = $this->createStub(Connection::class);
1742+
$connection->method('getRenameEmbeddedIdField')->willReturn(true);
1743+
$connection->method('getSession')->willReturn(null);
1744+
$grammar = new class ($connection) extends Grammar {
1745+
public function prepareFieldsForQuery(array $values, bool $root = true): array
1746+
{
1747+
return $values;
1748+
}
1749+
};
1750+
$connection->method('getQueryGrammar')->willReturn($grammar);
1751+
1752+
$builder = new Builder($connection, null, $this->createStub(Processor::class));
1753+
1754+
$mql = $builder->where('id', '=', 'abc123')->toMql();
1755+
1756+
$this->assertEquals(
1757+
['find' => [['id' => 'abc123'], ['typeMap' => ['root' => 'object', 'document' => 'array']]]],
1758+
$mql,
1759+
);
1760+
}
1761+
17391762
private function getBuilder(bool $renameEmbeddedIdField = true): Builder
17401763
{
17411764
$connection = $this->createStub(Connection::class);

0 commit comments

Comments
 (0)