我有一个最初使用Django创建的数据库,该数据库是为单个外键关联设置的,here is the JSON dump.
现在这将映射为:
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,
});
现在,sequelize抱怨它在类别模型上缺少一个外键,但是虽然一个成分上只有一个类别,但类别并不仅限于那一个成分。有人可以帮助我理解这种关联吗?
更新:对于最终答案,这只是一个错误的关联设置:
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',
});
答案 0 :(得分:2)
belongsToMany
用于关系N:M,因此ingredient_category
应该是第三个表。现在据我所知,你需要一个ingredients
1:N categories
的关系,所以Category
可以有很多成分,所以你应该使用hasMany
。
在你的情况下你不能使用hasOne
,因为它会在Categories
上创建成分的外键,而hasMany
会在成分上创建FK。
Category.hasMany(Ingredient, {
foreignKey: 'category_id',
constraints: false,
});
Ingredient.belongsTo(Category, {
// foreignKey: 'ingredientId',
constraints: false,
});
Here是文档: