如何在MySQL(Knex/Bookshelf)中的JSON字段中搜索子字符串?
我正在用书架/Knex做ORM。我有一个MySQL数据库,表中有一个JSON字段“data”。在该字段中,有一个键“title”和一个键“message”。我想返回所有在data.title或data.message中有子字符串“searchString”的行。我该怎么做 这样行吗如何在MySQL(Knex/Bookshelf)中的JSON字段中搜索子字符串?,mysql,knex.js,bookshelf.js,Mysql,Knex.js,Bookshelf.js,我正在用书架/Knex做ORM。我有一个MySQL数据库,表中有一个JSON字段“data”。在该字段中,有一个键“title”和一个键“message”。我想返回所有在data.title或data.message中有子字符串“searchString”的行。我该怎么做 这样行吗 qb.raw(`data->'title' LIKE ${searchString} OR data->'message LIKE ${searchString}`) 这项工作: const resul
qb.raw(`data->'title' LIKE ${searchString} OR data->'message LIKE ${searchString}`)
这项工作:
const results = await new Modelname()
.query((qb) => {
qb.whereRaw(
`JSONColumnName->
'$.JSONFieldName' LIKE "%${searchString}%"`)
})
.fetch();
“JSONColumnName”是JSON列的名称,“JSONFieldName”是该列中某个JSON字段的名称。这是如何在没有SQL注入孔的情况下实现的:
const results = await new Modelname()
.query((qb) => {
qb.whereRaw(
`JSONColumnName->
'$.JSONFieldName' LIKE ?`, [`%${searchString}%`])
})
.fetch();
你是想在实际的SQL查询中这样做吗?如果我必须下拉到knex.raw,是的。哦,我误解了这个问题。很抱歉此解决方案存在SQL注入漏洞。决不应将searchString直接插入SQL字符串。