javascript - 添加 knex.js .andWhere() 是条件为真
问题描述
我有这个 Knex 查询:
const customerProducts = db.sequelize.knex.select([
'CustomerProduct.id AS _id',
'CustomerProduct.last_delivered AS _lastDelivered',
'CustomerProduct.margin AS _margin',
'CustomerProduct.outlier AS _outlier',
'CustomerProduct.growth AS _growth',
'CustomerProduct.period AS _period',
'CustomerProduct.price AS _price',
'CustomerProduct.active AS _active',
'CustomerProduct.customer_id AS _customerId',
'CustomerProduct.product_id AS _productId',
'CustomerProduct.modified AS _modified',
'CustomerProduct.month_value AS _monthValue',
'customer.id AS _customer_id',
'customer.title AS _customer_title',
'customer.code AS _customer_code',
])
.from('customer_products AS CustomerProduct')
.innerJoin(
'customers AS customer',
'CustomerProduct.customer_id',
'customer.id',
)
.where(whereClause)
.limit(limit)
.offset(offset);
我想包含一个.andWhere()
仅在满足此条件时才添加到查询中的选项:
if (overdue === 'true')
我该怎么做呢?
解决方案
你可以这样做:
const query = db.sequelize.knex.select([
'CustomerProduct.id AS _id',
'CustomerProduct.last_delivered AS _lastDelivered',
'CustomerProduct.margin AS _margin',
'CustomerProduct.outlier AS _outlier',
'CustomerProduct.growth AS _growth',
'CustomerProduct.period AS _period',
'CustomerProduct.price AS _price',
'CustomerProduct.active AS _active',
'CustomerProduct.customer_id AS _customerId',
'CustomerProduct.product_id AS _productId',
'CustomerProduct.modified AS _modified',
'CustomerProduct.month_value AS _monthValue',
'customer.id AS _customer_id',
'customer.title AS _customer_title',
'customer.code AS _customer_code',
])
.from('customer_products AS CustomerProduct')
.innerJoin(
'customers AS customer',
'CustomerProduct.customer_id',
'customer.id',
);
if (overdue === 'true') {
query = query.where(whereClause)
}
const customerProducts = query.limit(limit).offset(offset);
推荐阅读
- jquery - System.ArgumentNullException:值不能为空。jQuery 数据表
- javascript - 单击后退按钮重定向到另一个页面
- powerapps - 提交新项目表单并打开同一项目进行编辑
- javascript - 电子分布构建显示空白页
- c# - 如何过滤从excel文件导入的datagridview中的列
- c++ - C++20 中的指定初始化器
- spring - Spring Stomp 慢速连接
- ios - Swift 我如何对服装尺码列表(例如 XL、S、2XL、XXS)进行排序?
- javascript - 回调是如何传递给函数的?
- amazon-web-services - S3跨账户复制不复制文件