Sequelize Associations

There are is four type of associations.

  1. A.hasOne(B); // A is source and B is target
  2. A.belongsTo(B);
  3. A.hasMany(B);
  4. 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