[英]Sequelize insert data with association
...
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不能為null
為什么Vegetable.recipeId不填充Recipe.id?
是否有最佳做法來插入具有關聯的數據?
在hasMany選項中未定義外鍵時,sequelize將自動生成它。 模型列和數據庫列的定義不匹配可能會導致這樣的錯誤。 您可能也可以定義外鍵。
Recipe.association = models => {
Recipe.hasMany(models.Vegetable, {foreignKey: 'recipeId', as: 'vegetables'});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.