Sequelize中$ and内的多个$ or查询

时间:2019-08-14 09:55:04

标签: node.js sequelize.js

我想在AND语句之后做OR语句。我想做类似...... WHERE性别='女性'AND(提取(dow从开始)= 2或extract(dow从开始)= 3)

let userWhereQuery = {}
let appointmentWhereQuery = {}

        if (gender != 'none') {
            userWhereQuery['$and'] = sequelize.literal(`lower(gender) = '${gender.toLowerCase()}'`)
        }

        if (days != '') {
            let daysOr = []
            for (let i = 0; i < days.length; i++) {
                let dayOr = {
                   ['$or']: sequelize.literal(`extract(dow from start) = ${days[i]}`)
                }
                daysOr.push(dayOr)
            }

            appointmentWhereQuery['$and'] = daysOr
        }

我得到的错误

Unhandled rejection Error: Invalid value { '$or':
   Literal {
     val: 'extract(dow from "therapistAppointments"."start") = 1' } }

1 个答案:

答案 0 :(得分:0)

您收到该错误,因为它无法识别运算符别名。 这是一个示例,可以给您一个想法:

const Op = Sequelize.Op;

const operatorsAliases = {
  $and: Op.and,
  $or: Op.or,
  $eq: Op.eq
};

要使用:

someMethod() => {
  var whereObj = {
          where: {
              gender: 'female',
              [Op.and]: [
                { days: {[Op.eq]: 2 }},
                { days: {[Op.eq]: 3 }}
              ]
          }
  };
  return whereObj;
}