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

时间:2019-01-20 06:01:02

标签: node.js knex.js

我需要根据接收到的参数用where子句创建一个查询,但是我不知道如何在where子句中包括一些参数。在下面的代码中,前四个条件(customerId,companyId,invoiceId和open)运行良好,但我不知道如何包括其他条件(closed,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))
}

1 个答案:

答案 0 :(得分:1)

参阅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)