我尝试将数组字符串化,因为我将其保存到我的mysql数据库中,并在检索时解析它,但我得到了#34;字符串不能代表数组"。是否可以使用sequelize更改getter中的类型,如果是这样,将如何完成?
choices: {
type:Sequelize.TEXT,
get(){
var val = this.getDataValue('choices');
return val ? JSON.parse(val):null;
},
set(val){
if(val && typeof(val)!=='string'){
val = JSON.stringify(val);
}
this.setDataValue('choices',val);
}
},
答案 0 :(得分:0)
这对sequelize或mysql来说不是问题。这是我的GraphQL突变的一个问题,我必须覆盖一个类型
import { attributeFields } from "graphql-sequelize";
import { GraphQLList, GraphQLString } from "graphql";
import { Question } from "../schemas/Question";
import ResponsePayload from "../schemas/ResponsePayload";
import _ from "lodash";
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
const CreateQuestion = {
type: ResponsePayload,
args: base,
resolve: ...
};
export { CreateQuestion };
特别是我必须改变
var base = attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
});
到
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
这会覆盖选择的类型,在sequelize模型中定义为String,但就GraphQL而言,需要是一个数组。