diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd240b43..5ec142b46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,11 @@ # Changelog All notable changes to this project will be documented in this file. -## [4.3.0] - unreleased +## [4.4.0] - unreleased + +* Support collection name prefix by @GromNaN in [#2930](https://github.com/mongodb/laravel-mongodb/pull/2930) + +## [4.3.0] - 2024-04-26 * New aggregation pipeline builder by @GromNaN in [#2738](https://github.com/mongodb/laravel-mongodb/pull/2738) * Drop support for Composer 1.x by @GromNaN in [#2784](https://github.com/mongodb/laravel-mongodb/pull/2784) diff --git a/src/Connection.php b/src/Connection.php index 0c5015489..90c77501d 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -66,6 +66,8 @@ public function __construct(array $config) // Select database $this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config)); + $this->tablePrefix = $config['prefix'] ?? ''; + $this->useDefaultPostProcessor(); $this->useDefaultSchemaGrammar(); @@ -109,7 +111,7 @@ public function table($table, $as = null) */ public function getCollection($name) { - return new Collection($this, $this->db->selectCollection($name)); + return new Collection($this, $this->db->selectCollection($this->tablePrefix . $name)); } /** @inheritdoc */ diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 262c4cafc..bbcd50574 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -178,6 +178,8 @@ public function testConnectionConfig(string $expectedUri, string $expectedDataba $this->assertSame($expectedUri, (string) $client); $this->assertSame($expectedDatabaseName, $connection->getMongoDB()->getDatabaseName()); + $this->assertSame('foo', $connection->getCollection('foo')->getCollectionName()); + $this->assertSame('foo', $connection->collection('foo')->raw()->getCollectionName()); } public function testConnectionWithoutConfiguredDatabase(): void @@ -200,6 +202,20 @@ public function testCollection() $this->assertInstanceOf(Builder::class, $collection); } + public function testPrefix() + { + $config = [ + 'dsn' => 'mongodb://127.0.0.1/', + 'database' => 'tests', + 'prefix' => 'prefix_', + ]; + + $connection = new Connection($config); + + $this->assertSame('prefix_foo', $connection->getCollection('foo')->getCollectionName()); + $this->assertSame('prefix_foo', $connection->collection('foo')->raw()->getCollectionName()); + } + public function testQueryLog() { DB::enableQueryLog();