0

So there are a lot of answers that explain how you model a Many-to-Many relationship in sequelizejs using hasMany() etc. But none of them has explained how and where do you store attributes which are created due to such an association, for eg: A customer can belong to or have many merchants and a merchant can have many customers, one such attribute of this relationship is a unique customer_id for a particular merchant-cutomer. Now where should this key(and any other detail) reside if we follow this: Stackoverflow answer

Community
  • 1
  • 1
Anmol
  • 303
  • 2
  • 14

1 Answers1

2

If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:

Customer = sequelize.define('customer', {})
Merchant = sequelize.define('merchant', {})
MerchantCustomers = sequelize.define('merchant_customers', {
    customer_id: DataTypes.INTEGER
})

Merchant.belongsToMany(Customer, { through: MerchantCustomers })
Customer.belongsToMany(Merchant, { through: MerchantCustomers })

customer.addMerchant(merchant, { customer_id: 42 })

http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations

To access the join table attributes:

c.getMerchants().then(function (merchants) {
  merchants[0].merchant_customer.customer_id // Or perhaps merchant_customers, can't remember
});
Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66
  • That's good but what difference would it make if I use hasMany() instead of belongsToMany? And how can I later retrieve these attributes from MerchantCustomer, because I'll either have c.getMerchant() or m.getCustomer(). Sorry but official docs are little confusing :/ – Anmol May 22 '15 at 07:04
  • hasMany is for 1:m, while belongsToMany if for n:m. As for retrieve, see my edit – Jan Aagaard Meier May 22 '15 at 07:43