sequelize-docs-Zh-CN
sequelize-docs-Zh-CN copied to clipboard
如何根据前端给过来的参数判断查询条件
比如前端传一个为 name 的参数,如果为空,则查询全部,不为空则查询所有
Model.findAll({
where: {
name: query.name
}
})
我该如何判断这里query.name
如果为空,就不要有name这个条件?
试过三目运算符置为 undefined
,可是出来的查询条件是 where name=null
还是说我只能把where拎出来,用if-else判断来加入条件,再做查询呢
if(!query.name) delete query.name
?
@whtiehack 现在是
const where = {};
if (query.name) {
Object.assign(where, { name: query.name });
}
Model.findAll({ where })
就是想问是否有更简洁的写法
@EasonYou 最后你是咋写的? 我觉得应该没有比你答案更简单的写法了
@happyzhanls let name = query.name Object.assign({}, name && {name})
真是超级小白。
Model.findAll(query.name ? {
where: {
name: query.name
}
} : {});
封装一个方法
/**
* 根据传入的数据生成 sequelize 的生成语句
* @param {array} arr data
* @param {object} options options
*/
genOpSQL(arr, options = {}) {
const operators = options.operators || 'and';
const sequelize = this.app.Sequelize;
const { Op } = sequelize;
const sqls = arr.map(val => {
const { op, field, cast, value } = val;
if (value === undefined) return {};
if (!op && !cast) {
return { [field]: value };
}
if (cast) {
return op ? sequelize.where(
sequelize.cast(sequelize.col(field), cast),
{ [Op[op]]: this.getOpSQL(op, value) }
) : sequelize.where(
sequelize.cast(sequelize.col(field), cast),
value
);
}
return {
[field]: { [ Op[op] ]: this.getOpSQL(op, value) },
};
});
return {
[Op[operators]]: sqls,
};
},
然后这么调用
const publisherList = await service.app.list({
where: ctx.genOpSQL([
{ field: 'userId', value: pubId },
{ op: 'in', field: 'id', value: ids },
{ op: 'iLike', field: 'username', value: name },
]),
});