У меня есть таблица RecipeIngredient, которая содержит 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»? Имя столбца - «component_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;
};
RecipeIngredient:
'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;
};