Skip to content

QueryBuilder multiply and divide support #3373

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

Open
wants to merge 3 commits into
base: 5.x
Choose a base branch
from

Conversation

faissaloux
Copy link

Hello 👋🏻

In this PR I have added multiply and divide to QueryBuilder .

Usage

DB::table('users')->where('name', 'John Doe')->multiply('salary');    // "salary" * 1
DB::table('users')->where('name', 'John Doe')->multiply('salary', 2); // "salary" * 2
DB::table('users')->where('name', 'John Doe')->divide('salary');      // "salary" / 1
DB::table('users')->where('name', 'John Doe')->divide('salary', 2);   // "salary" / 2

Checklist

  • Add tests and ensure they pass

@faissaloux faissaloux requested a review from a team as a code owner April 26, 2025 21:23
@faissaloux faissaloux requested a review from GromNaN April 26, 2025 21:23
Copy link
Member

@GromNaN GromNaN left a comment

Choose a reason for hiding this comment

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

Thanks for this nice feature that leverage MongoDB update operator.

Could you tell me a bit more about your use-case?

@faissaloux
Copy link
Author

Could you tell me a bit more about your use-case?

Case of storing price in cents

We need to get the price converted from cents to USD.

DB::table('products')->where('title', 'socks')->divide('price', 100);

Case of adding tax

DB::table('products')->where('title', 'socks')->multiply('price', 1.2);

@faissaloux faissaloux requested a review from GromNaN April 30, 2025 21:25
* @param float|int $amount
* @return int
*/
public function multiply($column, $amount = 1, array $extra = [], array $options = [])
Copy link
Member

Choose a reason for hiding this comment

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

$amount should not have a default value. Multiplying by 1 is no-op, unless you have extra values.

$user = DB::table('users')->where('name', 'Robert Roe')->first();
$this->assertNull($user->salary);
$user = DB::table('users')->where('name', 'Mark Moe')->first();
$this->assertEquals(0, $user->salary);
Copy link
Member

Choose a reason for hiding this comment

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

When the field doesn't exist, this operation should not create it as it will always be 0.

Suggested change
$this->assertEquals(0, $user->salary);
$this->assertNull($user->salary);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants