【问题标题】:Sequelize insert data with association用关联序列化插入数据
【发布时间】:2019-01-07 16:39:37
【问题描述】:

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 Violation: Vegetable.recipeId 不能为空

为什么 Vegetable.recipeId 没有用 Recipe.id 填充?

是否存在通过关联插入数据的最佳做法?

【问题讨论】:

    标签: javascript node.js express sequelize.js


    【解决方案1】:

    当 hasMany 选项中没有定义外键时,sequelize 会自动生成。模型和数据库列定义的不匹配可能会导致这样的错误。你可能也定义了外键。

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

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2014-01-19
      • 2013-11-07
      相关资源
      最近更新 更多