Sequelize如果没有提供查询,请删除“where”?

问题描述 投票:0回答:1

所以我基本上将一些查询字符串传递给我的端点以用作过滤器,我正在使用Sequelize。

我知道我可以使用where来过滤/查找记录,但我想这样做,如果我不提供查询字符串,它就会被忽略。

当前:

const { status } = req.query;

const tickets = await models.Ticket.findAndCountAll({
  where: {
    status,
  },
  attributes: [
    'id',
    'status'
  ],
});

如果我没有将状态作为查询字符串传递,则由于where无法执行而失败。我也尝试过将undefined传递给它,但没有运气,它错误地说出来; ERROR: WHERE parameter "status" has invalid "undefined" value

总而言之,我想做到这一点,如果我提供查询字符串,它们会被插入到where子句中,但如果它们不是,那么它就会被忽略。

sequelize.js
1个回答
0
投票

如果您知道where具有Sequelize可以使用的值,那么它只是包含status选项的情况。

const { status } = req.query;

// declare our query options
const options = {
    where: {},
    attributes: [
        'id',
        'status'
    ]
};

// if status has a value (!== undefined), include it in the query
if (status !== undefined)
    options.where.status = status;

const tickets = await models.Ticket.findAndCountAll(options);
© www.soinside.com 2019 - 2024. All rights reserved.