Reputation: 255
...
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 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
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