Skip to content

Commit

Permalink
PHPORM-227 Fix single document upsert (#3100)
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN authored Aug 26, 2024
1 parent 80694e4 commit efab63b
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
5 changes: 5 additions & 0 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
5 changes: 2 additions & 3 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
5 changes: 2 additions & 3 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down

0 comments on commit efab63b

Please sign in to comment.