如何在具有关系属性的 Sequelize Js 中实现多对多关系?

How to implemet a Many-to-Many relationship in Sequelizejs which also have relationship attributes?

所以有很多答案解释了如何在 sequelizejs 中使用 hasMany() 等对 多对多关系 建模。但是 none 其中解释了如何以及在哪里存储由于这种关联而创建的属性,例如:一个客户可以属于或拥有多个商家,一个商家可以有多个客户,这种关系的一个这样的属性是特定商家客户的唯一 customer_id。现在,如果我们遵循这个,这个密钥(和任何其他细节)应该在哪里:Whosebug answer

如果你想在连接 table 中添加额外的属性,你可以在定义关联之前在 sequelize 中为连接 table 定义一个模型,然后告诉 sequelize 它应该使用那个加入模型,而不是创建新模型:

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

要访问联接 table 属性:

c.getMerchants().then(function (merchants) {
  merchants[0].merchant_customer.customer_id // Or perhaps merchant_customers, can't remember
});