Sequelize动态查询参数

5

我正在使用前端MVC框架将查询参数以JSON格式作为req.query.p发送,关键点在于这可能是一个动态的键和值,例如:

req.query.p = {nombre : 'juan'}

或者

req.query.p = {pais : 'chile'}

所以我需要键和值,将它们放在where语句中,类似于这样。
exports.select = function(req, res){
    console.log('=> GET | Obtener peliculas'.bold.get);
        db.Pelicula
            .findAndCountAll({
                limit : req.query.limit,
                offset : req.query.offset,
                where : req.query.p ? [req.query.p.KEY + " = ?", req.query.p.VAL] : null
            })
            .success(function(resp){
                console.log(JSON.stringify(resp.rows, null, 4).bold.get);
                res.json({peliculas : resp.rows, meta : { total : resp.count}});
            });
}
3个回答

6

where参数可以是一个对象,因此您可以只传递where:req.query.p


谢谢!它可以工作 :P。顺便问一下,如果我想将多个参数传递给我的查询,应该如何处理?哪种方法是正确的? - jFranciscov
where: { arg1: something, arg2: somethingelse } - 普通的 JavaScript 对象 - Jan Aagaard Meier
那里的操作是什么?“...其中arg1 = something AND/OR?arg2 = somethingelse” - jFranciscov
默认是AND。如果你想使用OR,请使用where: sequelize.or({ arg1: something }, { arg2: somethingelse })。我建议您查看http://sequelizejs.com/上的指南和http://github.com/sequelize/sequelize/wiki/API-Reference上的API文档。 - Jan Aagaard Meier

0

使用ES6和动态属性,我会这样做

const { Op } = require("sequelize");

const from = new Date()
// const to = new Date().setMinutes(40)
const to = null

let where = {
    timestamp: {
        [Op.or]: {}
    }
}

if (from) {
    where.timestamp[Op.or][Op.gte] = new Date(from)
}
if (to) {
    where.timestamp[Op.or][Op.lte] = new Date(to)
}
console.log(where);

Model.find({ where })

0
通常我会放整个对象,所以如果它为空,它将正常工作,就像没有条件WHERE一样。 您不需要在where中添加{},因为来自req.query的对象已经有了。
const filter = req.query;
example= await ModelExample.findAndCountAll({
               where:
                filter
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接