gpt4 book ai didi

mysql - GraphQL Mutation 不允许我将数据添加到具有非空违规错误的 mysql 表

转载 作者:行者123 更新时间:2023-12-03 22:26:09 27 4
gpt4 key购买 nike

我正在使用 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' })

关于mysql - GraphQL Mutation 不允许我将数据添加到具有非空违规错误的 mysql 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239950/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com