将多对多关系引用错误的列名

  • 本文关键字:错误 引用 关系 sequelize.js
  • 更新时间 :
  • 英文 :


我有一个食谱成分表,其中包含食谱和成分表的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,

我的配置示例.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,
},
};

最新更新