gpt4 book ai didi

node.js - 如何在 Knex.js 中动态创建 where 条件?

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:33 33 4
gpt4 key购买 nike

我需要根据收到的参数使用where子句创建一个查询,但我不知道如何在where子句中包含一些参数。在下面的代码中,前四个条件(customerId、companyId、invoiceId 和 open)运行良好,但我不知道如何包含其他条件(close、openedFrom 和openedTo)。

const getByParams = (req, res) => {

const conditions = {}
if (req.query.customerId) conditions['wo.customerId'] = req.query.customerId
if (req.query.companyId) conditions['wo.companyId'] = req.query.companyId
if (req.query.invoiceId) conditions['wo.invoiceId'] = req.query.invoiceId
if (req.query.open) conditions['wo.finishedAt'] = null

const onlyClosed = req.query.closed ? 'wo.finishedAt != null' : ''
const openedFrom = req.query.openedFrom ? `wo.openingAt >= ${req.query.openedFrom}` : ''
const openedTo = req.query.openedTo ? `wo.openingAt <= ${req.query.openedTo}` : ''

app.db('workOrders as wo')
.select('wo.*',
'wos.serviceId',
'wos.cost',
'srv.name as serviceName')
.leftJoin('workOrderServices as wos', 'wo.id', 'wos.workOrderId')
.leftJoin('services as srv', 'wos.serviceId', 'srv.id')
.whereNull('wo.canceledAt')
.where(conditions)
.then(wo => {
const json = JSON.stringify(wo)
const newJson = convertJson(json)
res.status(200).send(newJson)
})
.catch(err => res.status(500).send(err))
}

最佳答案

引用https://knexjs.org/#Builder-where

试试这个:

.where((builder) => {

if (req.query.customerId)
builder.where('wo.customerId', req.query.customerId);

if (req.query.companyId)
builder.where('wo.companyId', req.query.companyId);

if (req.query.invoiceId)
builder.where('wo.invoiceId', req.query.invoiceId);

if (req.query.open)
builder.whereNull('wo.finishedAt');

// so on..

});

而不是

.where(conditions)

关于node.js - 如何在 Knex.js 中动态创建 where 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274014/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com