我们有一个包含三个表的多对多mySQL Db:
成分:成分池
module.exports = function (sequelize, DataTypes) {
const Ingredient = sequelize.define("Ingredients", {
name: DataTypes.STRING,
category: DataTypes.STRING,
important: DataTypes.BOOLEAN
}, {
timestamps: false
});
Ingredient.associate = function (models) {
console.log(models)
Ingredient.belongsToMany(models.Recipe, {
through: 'ingredient_recipes',
foreignKey: 'recipe_id'
});
};
return Ingredient;
};
食谱:一个单独的表格,其中包含食谱名称,不含食物等
function(sequelize, DataTypes) {
const Recipe = sequelize.define("Recipe", {
name: DataTypes.STRING,
numberOfIng: DataTypes.INTEGER,
link: DataTypes.STRING,
ImgURL: DataTypes.STRING
}, {
timestamps: false
});
Recipe.associate = function (models) {
Recipe.belongsToMany(models.Ingredients, {
through: 'ingredient_recipes',
foreignKey: 'ingredient_id'
});
};
return Recipe;
};
我们的关联表是构建的,只包含每个表中的外键 .
我们正在努力弄清楚如何编写我们的post方法以在我们的食谱中包含我们想要的成分 . 例如,如何填充配方中包含的成分以填充我们的关联表?我的配方数据库表中是否需要额外的列?
现在,我们的代码只是创建新配料和新配方,但我们希望能够参考现有配料 .
db.Recipe.create(req.body, {
include: [
{ model: db.Ingredients }]
}).then(function (recipe) {
res.json(recipe);
})
.catch(err => {
console.log(err);
});
我只是不确定sequelize .create方法的语法,我们可以从现有的成分表中引用id . 任何帮助都会很棒 .