2017-11-10 130 views
0

我想将字符串数组存储到我的mysql数据库中,并在检索它时解析它,但我得到的“字符串不能表示数组”。是否可以改变类型的getter可能与sequ​​elize,如果是的话将如何做?在getter中改变类型 - 用graphql编组并行

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

这不是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而言,它需要是一个数组。