【发布时间】:2021-02-03 01:56:29
【问题描述】:
我使用 graphql API 并尝试将数据插入 Postgress 表并收到错误:
"message": "column \"UserId\" does not exist",
还有我的原始查询:
Executing (default): INSERT INTO "Recipes"
("id","title","ingredients","direction","createdAt","updatedAt","userId") VALUES
(DEFAULT,$1,$2,$3,$4,$5,$6)
RETURNING
"id","title","ingredients","direction","createdAt","updatedAt","userId","UserId";
问题是列 UserId 不在我的模型中,但 userId 是!而且我不知道为什么 Postgres 试图返回 UserId 列。 我的模特。 用户:
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
User.hasMany(models.Recipe)
}
};
User.init({
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'User',
});
return User;
};
食谱:
module.exports = (sequelize, DataTypes) => {
class Recipe extends Model {
static associate(models) {
Recipe.belongsTo(models.User, { foreignKey: 'userId' })
}
};
Recipe.init({
title: {
type: DataTypes.STRING,
allowNull: false
},
ingredients: {
type: DataTypes.STRING,
allowNull: false
},
direction: {
type: DataTypes.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'Recipe',
});
return Recipe;
};
我的 graphql 架构:
const typeDefs = gql`
type User {
id: Int!
name: String!
email: String!
recipes: [Recipe!]!
}
type Recipe {
id: Int!
title: String!
ingredients: String!
direction: String!
user: User!
}
type Query {
user(id: Int!): User
allRecipes: [Recipe!]!
recipe(id: Int!): Recipe
}
type Mutation {
createUser(name: String!, email: String!, password: String!): User!
createRecipe(
userId: Int!
title: String!
ingredients: String!
direction: String!
): Recipe!
}
`
graphql 解析器:
Mutation: {
async createRecipe (root, { userId, title, ingredients, direction }, { models }) {
return models.Recipe.create({ userId, title, ingredients, direction })
}
}
还有我的 grapql 请求:
mutation {
createRecipe(
userId: 1
title: "Sample 2"
ingredients: "Salt, Pepper"
direction: "Add salt, Add pepper"
) {
id
title
ingredients
direction
}
}
【问题讨论】:
标签: node.js postgresql graphql sequelize.js database-migration