DT
Drizzle Team10mo ago
hk

increase or decrease values

using the the db update, is there anyway to increase or decrease a number value without having to get it first from the database?
5 Replies
Mykhailo
Mykhailo10mo ago
Hello, @hk! Try something like this:
await db
.update(users)
.set({ logins: sql`${users.logins} + 1`})
.where(eq(users.id, id));
await db
.update(users)
.set({ logins: sql`${users.logins} + 1`})
.where(eq(users.id, id));
hk
hk10mo ago
yeah exactly what I tried and seems to work @solo is it possible to make the + like this?
const operator = isIncrease === true ? '+' : '-'
const operator = isIncrease === true ? '+' : '-'
hk
hk10mo ago
but it seems like sql operator is putting the value as the actual string '+' instead of just +
No description
Mykhailo
Mykhailo10mo ago
@hk ye, unfortunately, it doesn't work, but you can try this way:
const isIncrease = false;
const credit = 1;

const response = await db
.update(users)
.set({
logins: sql`${users.logins} + ${isIncrease ? credit : -credit}`,
})
const isIncrease = false;
const credit = 1;

const response = await db
.update(users)
.set({
logins: sql`${users.logins} + ${isIncrease ? credit : -credit}`,
})
hk
hk10mo ago
yeah that make sense thanks!
Want results from more Discord servers?
Add your server