利用Sequelize进行模糊查询的时候,参考别人的代码使用$like
运算符:html
const getArticleList = async (ctx) => { let { title } = ctx.query, titleFilter = title ? { title: { $like: `%${title}%` } } : {} ... await Article.findAndCountAll({ where: titleFilter, include: [ ... ], ... }) ... }
可是我运行时报错:git
而后老老实实翻中文文档改为这样以后,就运行正常了。github
const Sequelize = require('sequelize'); const Op = Sequelize.Op; let titleFilter = title ? { title: { [Op.like]: `%${title}%` } } : {}
据文档来讲,Op.like
是正儿八经的操做符,而$like
实际上是运算符别名,由于Sequelize 容许将特定字符串设置为操做符的别名。就是说,使用$like
的正确打开方式是:async
const Op = Sequelize.Op; const operatorsAliases = { $like: Op.like } const sequelize= new Sequelize(db, user, pass, { operatorsAliases })
这样子之后,咱们才能使用$like
代替[Op.like]
。ui
完~如有不足,请多指教,万般感谢!spa