gpt4 book ai didi

graphql - GraphQL 的 Sequelize 中的 OneToMany 关联。自定义外键

转载 作者:行者123 更新时间:2023-12-03 22:21:05 25 4
gpt4 key购买 nike

我正在尝试在 Sequelize 的帮助下为 GraphQL 创建 Apollo 服务器。
我遵循了 Sequelize 的文档和一些教程,但我仍然有错误:User.hasMany(models.Recipe);Recipe.belongsTo(models.User, { foreignKey: 'userId'} );但是当我在 GraphQL 中执行一个变更以在我的数据库中添加一个新的 Recipe 时,我观察了我的控制台,它正在执行以下查询:

INSERT INTO "Recipe" ("id","title","ingredients","direction", "userId") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","title","ingredients","direction","userId", **"UserId"**;
它在 RETURNING 中比预期多一个字段,什么返回和错误,我不知道为什么。
"message": "Doesn't exist column «UserId»",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createRecipe"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"name": "SequelizeDatabaseError",
"parent": {
"length": 242,
"name": "error",
"severity": "ERROR",
"code": "42703",
"hint": "You probably want to refer column «Recipe.userId».",
我知道我可以更改外键并以大写字母('UserId')命名,这可以解决问题,但我希望能够自定义我自己的外键。
根据要求,这些是我的迁移:
await queryInterface.createTable('Recipe', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
allowNull: false
},
title: {
allowNull: false,
type: Sequelize.STRING
},
ingredients: {
allowNull: false,
type: Sequelize.STRING
},
direction: {
allowNull: false,
type: Sequelize.STRING
}
});

await queryInterface.createTable('User', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
allowNull: false,
type: Sequelize.STRING
},
email: {
allowNull: false,
type: Sequelize.STRING
},
password: {
allowNull: false,
type: Sequelize.STRING
}
});
这是模型/recipe.js:
module.exports = (sequelize, DataTypes) => {
const Recipe = sequelize.define('Recipe', {
title: {
type: DataTypes.STRING,
allowNull: false
},
ingredients: {
type: DataTypes.STRING,
allowNull: false
},
direction: {
type: DataTypes.STRING,
allowNull: false
}
}, {
modelName: 'Recipe',
freezeTableName: true,
timestamps: false
});
Recipe.associate = function(models) {
Recipe.belongsTo(models.User);
};
return Recipe;
};
这是schema.js:
const { gql } = require('apollo-server')

const typeDefs = gql`
type Query {
user(id: Int!): User
allRecipes: [Recipe!]!
recipe(id: Int!): Recipe
}

type User {
id: Int!
name: String!
email: String!
recipes: [Recipe!]!
}

type Recipe {
id: Int!
title: String!
ingredients: String!
direction: String!
user: User!
}

type Mutation {
createUser(name: String!, email: String!, password: String!): User!
createRecipe(
userId: Int!
title: String!
ingredients: String!
direction: String!
): Recipe!
}
`

module.exports = typeDefs
谢谢!

最佳答案

您还应该在 foreignKey 中指明 hasMany 选项:

User.hasMany(models.Recipe, { foreignKey: 'useId' })

关于graphql - GraphQL 的 Sequelize 中的 OneToMany 关联。自定义外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64284427/

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