...
var Vegetable = sequelize.define('Vegetable', {
recipeId: { allowNull: false, ... },
name: { ... },
});
Vegetable.association = models => {
Vegetable.belongsTo(models.Recipe);
};
...
...
var Recipe = sequelize.define('Recipe', {
id: { ... },
name: { ... },
...
});
Recipe.association = models => {
Recipe.hasMany(models.Vegetable, {as: 'vegetables'});
};
Recipe.insert = recipe => {
const { Vegetable } = require('./vegetable');
return Recipe.create({
name: 'asdf',
vegetables: [{name: 'asdf'}],
...
}, {
include: [{
model: Vegetable,
as: vegetables',
}],
});
};
...
SequelizeValidationError:notNull违规:Vegetable.recipeId不能为空
为什么Vegetable.recipeId不能用Recipe.id填充?
是否存在插入关联数据的最佳实践?
答案 0 :(得分:0)
在hasMany选项中未定义外键时,sequelize将自动生成它。模型列和数据库列的定义不匹配可能会导致这样的错误。您可能也可以定义外键。
Recipe.association = models => {
Recipe.hasMany(models.Vegetable, {foreignKey: 'recipeId', as: 'vegetables'});
};