Bat*_*rka 4 mysql json node.js sequelize.js
我的 MYSQL 中有行,我需要 Sequelize.js 查询。
每行都有 JSON 类型的 col,例如:
[
{id: 1234, blah: "test"},
{id: 3210, blah: "test"},
{id: 5897, blah: "test"}
]
Run Code Online (Sandbox Code Playgroud)
我已经id
并且需要选择将其包含id
在数组中至少一个对象中的行。
小智 7
原始 mysql 查询将是这样的:
SELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{"id": 1234}');
Run Code Online (Sandbox Code Playgroud)
简单的续集示例:
const { fn, col, cast } = this.sequelize;
const User = this.sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
comments: DataTypes.JSON,
defaultValue: [],
})
User.findAll({
where: fn('JSON_CONTAINS', col('comments'), cast('{"id": 1234}', 'CHAR CHARACTER SET utf8')),
})
.then(users => console.log('result', users.map(u => u.get())))
.catch(err => console.log('error', err));
Run Code Online (Sandbox Code Playgroud)
Cast 函数用于对“id”周围的双引号进行转义,以避免错误的查询字符串,如下所示:
SELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{\"id\": 1234}');
Run Code Online (Sandbox Code Playgroud)
还有一个肮脏的 mysql 查询示例(不要使用它):
SELECT * FROM `user` WHERE `comments` LIKE '%"id": 1234%';
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2903 次 |
最近记录: |