I have a database that was originally created with Django that was setup for a single foreign key association, here is the JSON dump.
Now this would be mapped as:
export const Category = sequelize.define(
'category',
{
name: { type: Sequelize.STRING, unique: true },
},
{
timestamps: false,
tableName: 'ingredients_category',
}
);
export const Ingredient = sequelize.define(
'ingredient',
{
name: { type: Sequelize.STRING, unique: true },
notes: { type: Sequelize.TEXT, defaultValue: '' },
category_id: {
type: Sequelize.INTEGER,
references: {
model: Category,
key: 'id',
},
},
},
{
timestamps: false,
tableName: 'ingredients_ingredient',
}
);
Category.belongsToMany(Ingredient, {
foreignKey: 'category_id',
constraints: false,
through: 'ingredient_category',
});
Ingredient.hasOne(Category, {
// foreignKey: 'ingredientId',
constraints: false,
});
Now sequelize complains that it is missing a foreign key on the Category model, but while there is only a single category on an ingredient the categories are not restricted to that one ingredient. Can someone help me to make sense of this association?
UPDATE: For the final answer it was just an incorrect association setup:
export const Category = sequelize.define(
'category',
{
name: { type: Sequelize.STRING, unique: true },
},
{
timestamps: false,
tableName: 'ingredients_category',
}
);
export const Ingredient = sequelize.define(
'ingredient',
{
name: { type: Sequelize.STRING, unique: true },
notes: { type: Sequelize.TEXT, defaultValue: '' },
},
{
timestamps: false,
tableName: 'ingredients_ingredient',
}
);
Category.hasMany(Ingredient, {
foreignKey: 'category_id',
});
Ingredient.belongsTo(Category, {
foreignKey: 'category_id',
});