Sequelize Associations
There are is four type of associations.
- A.hasOne(B); // A is source and B is target
- A.belongsTo(B);
- A.hasMany(B);
- A.belongsToMany(B, { through: 'C' });
The A.hasOne(B) mean, foreign key defined in the target model (B).
The A.belongsTo(B) foreign key defined in the source model (A).
The A.hasMany(B) foreign key being defined in the target model (B).
The A.belongsToMany(B, { through: 'C' }) means relationship exists between A and B, using table C as junction table, which will have the foreign keys (aId and bId, for example).
In app.js we can define like this
Product.belongsTo(User, {constraints:true, onDelete:'CASCADE'})
User.hasMany(Product)
// foreign key is set in Product