因此,我基本上将一些查询字符串传递到我的端点以用作过滤器,并且我正在使用 Sequelize。
我知道我可以用来where过滤/查找记录,但我想让它这样,如果我不提供查询字符串,它就会被忽略。
当前的:
const { status } = req.query;
const tickets = await models.Ticket.findAndCountAll({
where: {
status,
},
attributes: [
'id',
'status'
],
});
Run Code Online (Sandbox Code Playgroud)
如果我不将状态作为查询字符串传递,它将失败,因为where无法执行。我也尝试传递undefined给它,但没有运气,它错误地说:
ERROR: WHERE parameter "status" has invalid "undefined" value
总而言之,我想这样做,如果我确实提供了查询字符串,它们就会被插入到子句中where,但如果没有,那么它就会被忽略。
这只是一个仅包含where您知道statusSequelize 可以使用的值的选项的情况。
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2731 次 |
| 最近记录: |