问题描述
我正在尝试向 Node Sequelize findAll 添加一个 where like 子句,使其表现得像 sql 查询 select * from myData where name like '%Bob%'
使用以下代码
I am trying to add a where like clause to a Node Sequelize findAll, to behave like the sql query select * from myData where name like '%Bob%'
with the below code
let data: Array<any> = await MyDataSequelizeAccess.findAll({
where: {
name: {
$like: `%Bob%`
}
}
});
返回以下错误
无效值 { '$like': '%Bob%' }
如何在我的 sequelize 对象上执行那种 where 通配符或 where like?
How can I perform that type of where wildcard or where like on my sequelize object?
let data: Array<any> = await MyDataSequelizeAccess.findAll({
where: {
name: `Bob`
}
});
这按预期工作,但我无法使用通配符.
This works as expected, but I cannot get the wildcard to work.
更新仍然没有骰子 - 根据 https://sequelize.readthedocs.io/en/latest/docs/querying/#operators我的语法看起来正确
updated still no dice - per https://sequelize.readthedocs.io/en/latest/docs/querying/#operators my syntax looks correct
我也在尝试(但失败)对 $not 做同样的事情
I'm also trying (and failing) to do the same with $not as in
let data: Array<any> = await MyDataSequelizeAccess.findAll({
where: {
name: {
$not: `Bob`
}
}
});
并得到与上面相同的错误 Invalid value { '$not': '%Bob%' }
and getting the same error as above Invalid value { '$not': '%Bob%' }
推荐答案
字符串运算符(例如 $operator
)是 Sequelize V5 的遗留问题 .您仍然可以以传统方式使用运算符执行查询,但必须使用运算符的别名设置连接(会有关于此的弃用警告)..You can still execute queries with operators the legacy way, but the connection has to be setup with aliases for operators (there will be a deprecation warning about this).
const Op = Sequelize.Op;
const operatorsAliases = {
$like: Op.like,
$not: Op.not
}
const connection = new Sequelize(db, user, pass, { operatorsAliases })
[Op.like]: '%Bob%' // LIKE '%Bob%'
$like: '%Bob%' // same as using Op.like (LIKE '%Bob%')
Sequelize.js
的更新文档在 Sequelize.Op
模块中提供了作为符号运算符的运算符.
The updated documentation for Sequelize.js
provides operators in the Sequelize.Op
module as Symbol operators.
Sequelize 默认使用 Symbol 操作符,将操作符注入查询的风险降到最低;建议继续使用符号运算符.
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
let data: Array<any> = await MyDataSequelizeAccess.findAll({
where: {
name: {
[Op.like]: '%Bob%'
}
}
});
这篇关于节点续集找到 $like 通配符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!