-
-
Notifications
You must be signed in to change notification settings - Fork 499
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
如何根据前端给过来的参数判断查询条件 #14
Comments
|
@whtiehack const where = {};
if (query.name) {
Object.assign(where, { name: query.name });
}
Model.findAll({ where }) 就是想问是否有更简洁的写法 |
@EasonYou |
@happyzhanls |
真是超级小白。 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 },
]),
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
比如前端传一个为 name 的参数,如果为空,则查询全部,不为空则查询所有
我该如何判断这里
query.name
如果为空,就不要有name这个条件?试过三目运算符置为
undefined
,可是出来的查询条件是where name=null
还是说我只能把where拎出来,用if-else判断来加入条件,再做查询呢
The text was updated successfully, but these errors were encountered: