关联关联插入数据

时间:2018-07-31 10:02:37

标签: javascript node.js express sequelize.js

vegetable.js

...
var Vegetable = sequelize.define('Vegetable', {
 recipeId: { allowNull: false, ... },
 name: { ... },
});

Vegetable.association = models => {
 Vegetable.belongsTo(models.Recipe);
};
...

recipe.js

...
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填充?

是否存在插入关联数据的最佳实践?

1 个答案:

答案 0 :(得分:0)

在hasMany选项中未定义外键时,sequelize将自动生成它。模型列和数据库列的定义不匹配可能会导致这样的错误。您可能也可以定义外键。

Recipe.association = models => {
 Recipe.hasMany(models.Vegetable, {foreignKey: 'recipeId', as: 'vegetables'});
};