[英]how can I avoid escape character \" when I use ‘Op.notLike ’ in function of "findAll " in eggjs model?
I have this code我有这个代码
async getHisDataByTime(startTime, endTime, ids) {
console.log("getHisDataByTime >>", startTime, endTime, ids)
const Op = this.ctx.app.Sequelize.Op;
const dataHis = await this.ctx.model.Datahis.findAll({
where: {
device_id: { [Op.in]: ids },
datetime: {
[Op.gte]: startTime,
[Op.lte]: endTime
},
data:{
[Op.notLike]: '%valid%',
}
},
//group:['device_id'],
order: [['datetime']],
attributes: ['device_id', 'datetime', 'data']
});
return dataHis;
}
which generates this sql command:生成此 sql 命令:
SELECT `device_id`, `datetime`, `data` FROM `data_his` AS `datahis`
WHERE `datahis`.`device_id` IN ('2019083107100024', '2020010303100002')
AND (`datahis`.`datetime` >= '2019-09-23 00:00:00'
AND `datahis`.`datetime` <= '2019-09-24 23:00:00')
AND `datahis`.`data` NOT LIKE '\"%valid%\"'
ORDER BY `datahis`.`datetime`;
I expected '%valid%'
,but actually got '\\"%valid%\\"'
.我期望
'%valid%'
,但实际上得到了'\\"%valid%\\"'
。 The escaped character \\"
appears automatically,and the mysql command performs as follows:转义字符
\\"
自动出现,mysql命令执行如下:
so, Op.notLike
does not work at all in this case.所以,
Op.notLike
在这种情况下根本不起作用。
after I remove the escape character \\"
and execute it in Navicat, the result is just what I want:我去掉转义符
\\"
,在Navicat中执行,结果正是我想要的:
but how can I avoid escape character \\"
in "findAll" to fix this out? I've compared my code with the official example below, however, useless. https://sequelize.org/master/manual/model-querying-basics.html但是如何避免在“findAll”中使用转义字符
\\"
来解决这个问题?我已经将我的代码与下面的官方示例进行了比较,但是没用 。https://sequelize.org/master/manual/model-querying-基础知识.html
So far, it is not known what caused the escape character,but there are two solutions here.到目前为止,不知道是什么导致了转义字符,但这里有两种解决方案。
1. public async query(sql: string, options: object): Promise using
2. JSON_CONTAINS_PATH to check the key of data
code for solution 2:解决方案2的代码:
async getHisDataByTime(startTime, endTime, ids) {
console.log("getHisDataByTime >>", startTime, endTime, ids)
const { Op } = this.app.Sequelize;
let validFn = this.app.Sequelize.fn("JSON_CONTAINS_PATH", this.app.Sequelize.col("data"), 'one', '$.valid');
const dataHis = await this.ctx.model.Datahis.findAll({
where: {
[Op.and]: [
{ device_id: { [Op.in]: ids } },
{
datetime: {
[Op.gte]: startTime,
[Op.lte]: endTime
}
},
this.app.Sequelize.where(validFn, 0)
]
},
//group:['device_id'],
order: [['datetime']],
attributes: ['device_id', 'datetime', 'data']
});
return dataHis;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.