diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c1c4d9c1..fa510e9aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog All notable changes to this project will be documented in this file. +## [4.7.2] - coming soon + +* Add `Query\Builder::upsert()` method with a single document by @GromNaN in [#3100](https://github.com/mongodb/laravel-mongodb/pull/3100) + ## [4.7.1] - 2024-07-25 * Fix registration of `BusServiceProvider` for compatibility with Horizon by @GromNaN in [#3071](https://github.com/mongodb/laravel-mongodb/pull/3071) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 1d4dcf153..23f2ec02c 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -732,6 +732,11 @@ public function upsert(array $values, $uniqueBy, $update = null): int return 0; } + // Single document provided + if (! array_is_list($values)) { + $values = [$values]; + } + $this->applyBeforeQueryCallbacks(); $options = $this->inheritConnectionOptions(); diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 57e49574f..24dc9a5ae 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -168,9 +168,8 @@ public function testUpsert() $this->assertSame('bar2', User::where('email', 'foo')->first()->name); // If no update fields are specified, all fields are updated - $result = User::upsert([ - ['email' => 'foo', 'name' => 'bar3'], - ], 'email'); + // Test single document update + $result = User::upsert(['email' => 'foo', 'name' => 'bar3'], 'email'); $this->assertSame(1, $result); $this->assertSame(2, User::count()); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 7924e02f3..ac35e8978 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -632,9 +632,8 @@ public function testUpsert() $this->assertSame('bar2', DB::collection('users')->where('email', 'foo')->first()['name']); // If no update fields are specified, all fields are updated - $result = DB::collection('users')->upsert([ - ['email' => 'foo', 'name' => 'bar3'], - ], 'email'); + // Test single document update + $result = DB::collection('users')->upsert(['email' => 'foo', 'name' => 'bar3'], 'email'); $this->assertSame(1, $result); $this->assertSame(2, DB::collection('users')->count());