我必须从当前将 JSON 存储为文本的 1 列中获取值:
col1: {"class":{"count":3,"number":25}}
所以当我使用带有选项的sequulize orm时:
..attributes: ['id', 'col1']..
它返回值:
"{\"class\":{\"count\":3,\"number\":25}}"
我如何使用类似的东西:
..attributes: ['id', sequelize.json('col1')]..
获取JSON格式的数据? 谢谢
我不知道
sequelize.json
...
您可以在列上使用 JSON.parse 和 getter。
sequelize.define('your_table', {
col1: {
type: DataTypes.TEXT,
get(val) { return JSON.parse(val) }
}
})
但是 Postgres(我认为 MySQL,尽管我在续集文档中没有看到它)具有 JSON 字段类型。他们会好很多。您可以通过任意嵌套的键和值进行查询。您还可以创建索引。同样,它们可能只能通过 Postgres 实现。
sequelize.define('your_table', {
col1: {
type: DataTypes.JSONB,
}
})
我想你在数据库中进行查找查询时需要设置
{raw: true}
。这将返回 json 对象
我遇到了和你一样的问题,这是我的解决方案:
sequelize.define("your_table", {
col1: {
type: Sequelize.STRING,
get: function () {
return JSON.parse(this.getDataValue("col1"));
}
}
})
以下是设置所有 Sequelize JSON 类型列的方法。这可以防止读取数据库时出错,尤其是在 MariaDB 中,其中 JSON 比 MYSQL 中的 LONGTEXT 长,而 MYSQL 中有特殊的 JSON 类型。
MyGreatJSONColumnName: {
type : DataTypes.JSON,
defaultValue : [],
get(){
let tab = this.getDataValue("MyGreatJSONColumnName");
if(typeof tab === 'string' || tab instanceof String) try{tab = JSON.parse(tab);}catch(e){tab=undefined};
if(!tab) return [];
else return tab;
}
}
或者如果你想要一个像柱这样的物体
MyGreatJSONColumnName: {
type : DataTypes.JSON,
defaultValue : {},
get(){
let tab = this.getDataValue("MyGreatJSONColumnName");
if(typeof tab === 'string' || tab instanceof String) try{tab = JSON.parse(tab);}catch(e){tab=undefined};
if(!tab) return {};
else return tab;
}
}