gpt4 book ai didi

sequelize.js - Sequelize 多对多关系引用错误的列名

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

我有一个 RecipeIngredient 表,其中包含 Recipe 和 Ingredient 表的 PK,如下所示:

'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('RecipeIngredients', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
recipe_id: {
type: Sequelize.INTEGER,
references: { model: 'Recipes', field: 'id' }
},
ingredient_id: {
type: Sequelize.INTEGER,
references: { model: 'Ingredients', field: 'id'}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('RecipeIngredients');
}
};

如果我只是尝试使用以下代码查询上表:
models.RecipeIngredient.findAll().then(all => console.log(all))

我收到以下错误:
Executing (default): SELECT "recipe_id", "ingredient_id", "createdAt", "updatedAt", "IngredientId", "RecipeId" FROM "RecipeIngredients" AS "RecipeIngredient";
Unhandled rejection SequelizeDatabaseError: column "IngredientId" does not exist

为什么 Sequelize 认为有一个名为“IngredientId”的列?列的名称是“ingredient_id”。

更新:添加了模态定义

食谱:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Recipe = sequelize.define('Recipe', {
name: DataTypes.STRING
}, {});
Recipe.associate = function(models) {
Recipe.belongsToMany(models.Ingredient, {
as: 'ingredients', through: { model: models.RecipeIngredient, foreignKey: 'recipe_id'}
})
// associations can be defined here
};
return Recipe;
};

成分:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Ingredient = sequelize.define('Ingredient', {
name: DataTypes.STRING
}, {});
Ingredient.associate = function(models) {
Ingredient.belongsToMany(models.Recipe, { as: 'recipes', through: { model: models.RecipeIngredient, foreignKey: 'ingredient_id'}})
};
return Ingredient;
};

配方成分:
 'use strict';
module.exports = (sequelize, DataTypes) => {
var RecipeIngredient = sequelize.define('RecipeIngredient', {
recipe_id: DataTypes.INTEGER,
ingredient_id: DataTypes.INTEGER
}, {});
RecipeIngredient.associate = function(models) {
// associations can be defined here
};
return RecipeIngredient;
};

最佳答案

在配置数据库的文件中,在里面放一个定义:

underscored: true,
underscoredAll: true,
freezeTableName: true,

我的 config.js 示例
require("dotenv").config();

module.exports = {
dialect: process.env.DB_DIALECT,
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
define: {
timestamps: true,
underscored: true,
underscoredAll: true,
freezeTableName: true,
},
};

关于sequelize.js - Sequelize 多对多关系引用错误的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62025455/

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