mysql - GraphQL Mutation 不允许我将数据添加到具有非空违规错误的 mysql 表中
问题描述
我正在使用 GraphQL、Sequelize 和 MySql 向客户表添加数据。在 GraphQl Mutation 中,我执行以下操作:
const db = require("./models");
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addClient: {
type: ClientType,
args: {
lastName: { type: new GraphQLNonNull(GraphQLString) },
firstName: { type: new GraphQLNonNull(GraphQLString) },
primaryPhoneNumber: { type: new GraphQLNonNull(GraphQLString) },
cellphone: { type: GraphQLString },
workPhone: { type: GraphQLString },
email: { type: GraphQLString },
UserId: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parentValue, args) {
let newClient = new db.Client({
lastName: args.lastName,
firstName: args.firstName,
primaryPhoneNumber: args.primaryPhoneNumber,
cellphone: args.cellphone,
workPhone: args.workPhone,
email: args.email,
UserId: args.UserId
});
console.log(newClient);
return db.Client.create(newClient);
}
}
}
});
但是我在 GraphiQL 上测试它时收到了这个错误:
{
"errors": [
{
"message": "notNull Violation: Client.lastName cannot be null,\nnotNull Violation:
Client.firstName cannot be null",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"addClient"
]
}
],
"data": {
"addClient": null
}
}
我相信这个错误来自sequelize,因为在我的模型中我定义了一些非空字段:
module.exports = function(sequelize, DataTypes) {
var Client = sequelize.define(
"Client",
{
lastName: {
type: DataTypes.TEXT,
allowNull: false,
len: [1]
},
firstName: {
type: DataTypes.TEXT,
allowNull: false,
len: [1]
},
primaryPhoneNumber: {
type: DataTypes.TEXT,
allowNull: true,
len: [1]
},
cellphone: {
type: DataTypes.TEXT,
allowNull: true,
len: [1]
},
workPhone: {
type: DataTypes.TEXT,
allowNull: true,
len: [1]
},
email: {
type: DataTypes.TEXT,
allowNull: true,
len: [1]
}
},
{
timestamps: false
}
);
Client.associate = function(models) {
// Associating Clients with Pets
// When a Client is deleted, also delete any associated Pets
Client.belongsTo(models.User);
Client.hasMany(models.Pet, {
onDelete: "cascade"
});
};
return Client;
};
这是我从前端的查询:
mutation {
addClient(lastName: "ali", firstName: "muhamed", primaryPhoneNumber:
"00990099009", email: "jalimaña@email.com", UserId: "14fb9610-4766-11ea-9a4e-
e130bc08c2aa") {
lastName,
firstName
}
}
有谁知道为什么会这样?任何帮助将不胜感激。
解决方案
Model.create
接受一个普通对象,其值应初始化模型实例。您不应该将现有的 Model 实例传递给它。相反,只需调用save
实例上的方法。
const instance = new SomeModel({ firstName: 'Bob' })
await instance.save()
这相当于
const instance = SomeModel.build({ firstName: 'Bob' })
await instance.save()
和
await SomeModel.create({ firstName: 'Bob' })
推荐阅读
- javascript - 如何避免专注于 slickGoTo 事件
- sql - 如何将许多(和不同的)单元格从一行合并到具有较少单元格的多行?
- unit-testing - 使用 mocha webpack 为 Vue.js 前端编写单元测试用例时找不到模块问题
- javascript - 使用 qrcode-reader [React-Native] 解码 QrCode 图像文件时出错
- selenium - 如何在 Java 中使用 Selenium 打开 chrome 开发者控制台?
- vb.net - Devexpress 合并 3 个数据库,但缺少一些数据
- rest - 使用 LDAP 服务器配置的 Hyperledger Composer 身份验证失败,并出现错误“用户配置文件中缺少电子邮件”
- android - Xamarin Android 状态栏字体颜色
- ios - 使用 Hyperloop 在 iOS Appcelerator 中播放 Youtube 视频
- c# - Telerik - 无法用数据填充网格