K
KyselyPogPEGA

Conditionally updating fields

How would i go about doing something like UPDATE table SET field = IF(condition, trueValue, falseValue) WHERE someCondition;, i can't exactly seem to find that in the docs Driver used: MySQL
PogPEGA
PogPEGA•19d ago
actually, this can be done with <ExpressionBuilder>.case(), but is it possible to write smth like id = id - 1 or would i be sticking to raw sql for scenarios like these?
Solution
Igal
Igal•19d ago
Hey 👋 Something like:
await db
.updateTable("person")
.set("children", (eb) =>
eb
.case()
.when("has_spouse", "=", eb.lit(1))
.then(eb("children", "+", eb.lit(1)))
.else(eb.ref("children"))
.end(),
)
.where("first_name", "=", "Bob")
.execute();
await db
.updateTable("person")
.set("children", (eb) =>
eb
.case()
.when("has_spouse", "=", eb.lit(1))
.then(eb("children", "+", eb.lit(1)))
.else(eb.ref("children"))
.end(),
)
.where("first_name", "=", "Bob")
.execute();
https://kyse.link/mqB8C eb.lit is optional here, you could just pass the 1s and have them parametrized. eb(...) allows creating all sorts of binary operations, where by default, the LHS is a column reference, and RHS is a value.