如果使用 knex 不存在,如何忽略列更新?
How to ignore a column update if not exist using knex?
我正在尝试使用此语法更新 table
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
exampleColumn: userInput,
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
现在 exampleColumn 可能存在于某些 table 中,也可能不存在,所以我处于一种情况,我想让这个尽可能动态化
是否有等同于此的语法
.update({
[payment]: userPayment,
exampleColumn?: userInput, // ? to update if exist if not ignore this line
})
作为解决方法,我在我的代码中添加了一个条件
if (!isExampleColumn) { /* I get this from a another function */
userInput = undefined;
}
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
exampleColumn: userInput, // if userInput is undefined then it will be ignored
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
但我认为有比这更好的解决方案。
你可以使用条件传播,它看起来像:
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
... isExampleColumn? {exampleColumn: userInput} : {},
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
由于 Knex 是一个 QueryBuilder,您还可以拆分“构建”部分。
const query = knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
});
if(isExampleColumn) {
query.update({exampleColumn: userInput})
}
const results = query
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
我正在尝试使用此语法更新 table
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
exampleColumn: userInput,
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
现在 exampleColumn 可能存在于某些 table 中,也可能不存在,所以我处于一种情况,我想让这个尽可能动态化
是否有等同于此的语法
.update({
[payment]: userPayment,
exampleColumn?: userInput, // ? to update if exist if not ignore this line
})
作为解决方法,我在我的代码中添加了一个条件
if (!isExampleColumn) { /* I get this from a another function */
userInput = undefined;
}
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
exampleColumn: userInput, // if userInput is undefined then it will be ignored
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
但我认为有比这更好的解决方案。
你可以使用条件传播,它看起来像:
knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
... isExampleColumn? {exampleColumn: userInput} : {},
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))
由于 Knex 是一个 QueryBuilder,您还可以拆分“构建”部分。
const query = knex(tableName)
.where("id", "=", userId)
.update({
[payment]: userPayment,
});
if(isExampleColumn) {
query.update({exampleColumn: userInput})
}
const results = query
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))