Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added two methods incrementEach and decrementEach #2550

Open
wants to merge 1 commit into
base: 4.1
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Query/Builder.php
Expand Up @@ -647,6 +647,29 @@ public function increment($column, $amount = 1, array $extra = [], array $option
return $this->performUpdate($query, $options);
}

public function incrementEach(array $columns, array $extra = [], array $options = [])
{

$query = ['$inc' => $columns];

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

// Protect
foreach ($columns as $column => $amount) {
$this->where(function ($query) use ($column) {
$query->where($column, 'exists', false);

$query->orWhereNotNull($column);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With cumulative conditions on all fields, no field will be incremented if at least 1 of the fields is null.

We'd be wise not to set any conditions at all and let the server return an error.

});
}

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

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

/**
* @inheritdoc
*/
Expand All @@ -655,6 +678,17 @@ public function decrement($column, $amount = 1, array $extra = [], array $option
return $this->increment($column, -1 * $amount, $extra, $options);
}

public function decrementEach(array $columns, array $extra = [], array $options = [])
{
$decrement = [];

foreach ($columns as $column => $amount) {
$decrement[$column] = -1 * $amount;
}

return $this->incrementEach($decrement, $extra, $options);
}

/**
* @inheritdoc
*/
Expand Down