양정훈
양정훈

Reputation: 255

Sequelize insert data with association

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',
  }],
 });
};
...

Result

SequelizeValidationError: notNull Violation: Vegetable.recipeId cannot be null

Why Vegetable.recipeId doesn't fill with Recipe.id?

Is there best practice to insert data with association?

Upvotes: 2

Views: 5058

Answers (1)

Shahin Shemshian
Shahin Shemshian

Reputation: 376

When foreign key is not defined in hasMany options, sequelize will generate it automatically. The mismatch of model and database columns defenition may cause errors like this. you may probably define foreign keys too.

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

Upvotes: 3

Related Questions