简体   繁体   English

如何在 MySQL(Knex/书架)的 JSON 字段中搜索 substring?

[英]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.

相关问题 如何在 RDS 上正确使用带有 MySQL 的 Knex / Bookshelf - How to properly use Knex / Bookshelf with MySQL on RDS 如何在 BelongsToMany 连接表上的 Bookshelf/Knex 中查询? - How can I query in Bookshelf/Knex on a BelongsToMany join table? 如何使用子字符串而不是完整字符串在mysql中执行搜索? - How do i perform a search in mysql with a substring, instead of full string? 书架,Knex和mysql保存对象列表 - Bookshelf, Knex and mysql to save a list of an object 使用书架或Knex ORM选择MySQL JSON列数据类型内的特定字段 - SELECT specific fields inside the MySQL JSON Column datatype using bookshelf or Knex ORM 如何使用 Knex.js (MySQL) 执行 JSON_MERGE_PATCH? - How to do a JSON_MERGE_PATCH with Knex.js (MySQL)? 如何与书架和膝关节中的连接表进行交互? - How to interact with a join table in bookshelf and knex? 如何在不使用InvokeThen的情况下使用bookshelf js(和knex querybuilder)将多行插入mysql? - How to insert multiple rows into mysql using bookshelf js (and knex querybuilder) without using InvokeThen? 如何使用 bookshelf.js 或 knex 在 MySQL 中查询按距离与纬度、经度坐标排序的地点? - How to query places sorted by distance with lat, lng coordinates in MySQL with bookshelf.js or knex? 如何在Knex中使用MySQL MEMORY存储引擎? - How do I use the MySQL MEMORY storage engine with Knex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM