【发布时间】:2021-08-11 02:16:14
【问题描述】:
我无法在 Knex 中创建以下 SQL 查询:
SELECT * FROM tasks WHERE (code = 'export') AND (status = 'failed' OR status = 'complete')
使用代码:
const queryResult = await this.db('tasks')
.select('*')
.where(async function () {
if ('code' in query) {
this.where('code', query.code)
}
if ('status' in query) {
if (isArray(query.status)) {
return query.status.map(status => this.orWhere('status', status))
} else {
this.andWhere('status', query.status)
}
}
})
.orderBy('created_at', 'DESC')
当提供多个状态的数组时,它会忽略“code = export”值并选择所有内容。
【问题讨论】:
-
您不需要
orWhere和循环。只需使用whereIn('status', query.status) -
那是因为你正在构建一个像
code = 'exports' OR status = 'failed' OR status = 'complete'这样的查询——想想看,在这个代码路径中没有andWhere,只有orWhere!您需要将ORs 放入.andWhere(function () {})调用中以创建AND和括号,或者更好的是,在数组案例中使用code = 'export' AND status IN ('failed', 'complete')和andWhere(status, 'IN', query.status)。 -
.where()回调不是异步的
标签: javascript typescript knex.js