我正在使用节点js + sequelize。我想通过供应商,价格,交付选项等选定的选项来过滤产品的结果,但我无法理解如何使查询准确。
现在我正在这样做,但此方法仅在选择了所有过滤器(AND运算符)时有效。如果用户只选择1个过滤器或少数过滤器,我该怎么办?
let vendor = req.query.vendor;
let priceFrom = req.query.priceFrom;
let priceTo = req.query.priceTo;
let delivery = req.query.delivery
Product.findAll({
where: {
vendor_id: {
in: vendor
},
price: {
$between: [priceFrom, priceTo]
},
{
delivery: delivery
}
}
}).then(products => {
res.render('product', {products: products});
console.log(products)
});
我现在只有一种方法可以让它为每个场合编写很多if-else语句。
答案 0 :(得分:2)
首先检查查询参数并根据这些查询参数创建一个对象,如
let vendor = req.query.vendor;
let priceFrom = req.query.priceFrom;
let priceTo = req.query.priceTo;
let delivery = req.query.delivery
var options = {where: {}};
if(vendor) {
options.where.vendor_id = {$in: vendor}
}
if(priceFrom && priceTo) {
options.where.price = {$between: [priceFrom, priceTo]}
}
if(delivery) {
options.where.delivery = delivery
}
Product.findAll(options)
.then(products => {
console.log(products)
res.render('product', {products: products});
})