Skip to content

Commit

Permalink
Fix incrementEach to handle null values
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Jul 22, 2024
1 parent ce8317c commit cc64018
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
18 changes: 6 additions & 12 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -789,24 +789,18 @@ public function increment($column, $amount = 1, array $extra = [], array $option

public function incrementEach(array $columns, array $extra = [], array $options = [])
{
$query = ['$inc' => $columns];
$stage['$addFields'] = $extra;

if ($extra) {
$query['$set'] = $extra;
}

// Protect
// Not using $inc for each column, because it would fail if one column is null.
foreach ($columns as $column => $amount) {
$this->where(function ($query) use ($column) {
$query->where($column, 'exists', false);

$query->orWhereNotNull($column);
});
$stage['$addFields'][$column] = [
'$add' => [$amount, ['$ifNull' => ['$' . $column, 0]]],
];
}

$options = $this->inheritConnectionOptions($options);

return $this->performUpdate($query, $options);
return $this->performUpdate([$stage], $options);
}

/** @inheritdoc */
Expand Down
4 changes: 2 additions & 2 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1020,8 +1020,8 @@ public function testIncrementEach()
$this->assertEquals(8, $user['note']);

$user = DB::collection('users')->where('name', 'Robert Roe')->first();
$this->assertNull($user['age']);
$this->assertArrayNotHasKey('note', $user);
$this->assertSame(1, $user['age']);
$this->assertSame(2, $user['note']);

DB::collection('users')->where('name', 'Jane Doe')->incrementEach([
'age' => 1,
Expand Down

0 comments on commit cc64018

Please sign in to comment.