[英]How do I search for a substring in a JSON field in MySQL (Knex/Bookshelf)?
I'm using Bookshelf/Knex for an ORM.我正在为 ORM 使用 Bookshelf/Knex。 I've got a MySQL database, with a table which has a JSON field called "data."
我有一个 MySQL 数据库,其中一个表有一个名为“数据”的 JSON 字段。 Inside that field, there is a key "title" and a key "message."
在该字段内,有一个关键的“标题”和一个关键的“消息”。 I want to return all rows which have substring "searchString" in either data.title or data.message.
我想返回在 data.title 或 data.message 中具有 substring“searchString”的所有行。 How can I do this?
我怎样才能做到这一点?
Would this work?这行得通吗?
qb.raw(`data->'title' LIKE ${searchString} OR data->'message LIKE ${searchString}`)
This is how to do it without SQL injection hole:这是没有 SQL 注入孔的方法:
const results = await new Modelname()
.query((qb) => {
qb.whereRaw(
`JSONColumnName->
'$.JSONFieldName' LIKE ?`, [`%${searchString}%`])
})
.fetch();
This works:这有效:
const results = await new Modelname()
.query((qb) => {
qb.whereRaw(
`JSONColumnName->
'$.JSONFieldName' LIKE "%${searchString}%"`)
})
.fetch();
"JSONColumnName" is the name of the JSON column, "JSONFieldName" is the name of some JSON field inside that column. “JSONColumnName”是 JSON 列的名称,“JSONFieldName”是该列内的一些 JSON 字段的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.