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

How to sum values in update? #304

Open
neto737 opened this issue Nov 11, 2020 · 4 comments
Open

How to sum values in update? #304

neto737 opened this issue Nov 11, 2020 · 4 comments

Comments

@neto737
Copy link

neto737 commented Nov 11, 2020

Hi,

I'm using FluentPDO, and I haven't found anywhere how to sum a value in an update query

Like:

UPDATE `users` SET `balance` = `balance` + 100 WHERE `id` = 1;

I tried to do this way:

$query = static::getInstance()->update('users')
                ->set('`balance`', "`balance` + '{$amount}'")
                ->where('id', $userId);
        $query->execute();

But it doesn't work, is there another way to do this?

@cbornhoft
Copy link
Member

cbornhoft commented Nov 16, 2020

Hey @neto737, if you haven't solved this yet, what does the code above produce?

I see you're also using a mixture of bound params and value inserts which isn't recommended. Try something like:

$query = static::getInstance()->update('users')
                ->set('balance += ?', $amount)
                ->where('id = ?', $userId);

@neto737
Copy link
Author

neto737 commented Nov 17, 2020

Hey @neto737, if you haven't solved this yet, what does the code above produce?

I see you're also using a mixture of bound params and value inserts which isn't recommended. Try something like:

$query = static::getInstance()->update('users')
                ->set('balance += ?', $amount)
                ->where('id = ?', $userId);

Actually I tried this way, tried a lot of other ways to sum values in an update query, but nothing worked yet.

Nothing worked yet.

@neto737
Copy link
Author

neto737 commented Nov 17, 2020

Fixed using Literal class

        $query = static::getInstance()->update('users')
                ->set([
                    'balance' => new Literal('balance + ' . $amount)
                ])
                ->where('id', $userId);

@neto737 neto737 closed this as completed Nov 17, 2020
@cbornhoft
Copy link
Member

Great to hear!

I'm going to reopen this and mark as a potential bug to fix in 3.0. There should be a way to do this without forcing a Literal value.

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

No branches or pull requests

2 participants