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

时间:2015-05-21 12:50:01

标签: node.js sequelize.js

因此,有许多答案可以解释您如何使用sequelizejs等在hasMany()中对多对多关系进行建模。但是他们都没有解释如何并且您在哪里存储由于这种关联而创建的属性,例如:客户可以属于或拥有许多商家,而商家可以拥有许多客户,这种关系的一个这样的属性是特定商家的唯一customer_id- CUTOMER。现在,如果我们遵循以下内容,此键(以及任何其他详细信息)应驻留在何处:Stackoverflow answer

1 个答案:

答案 0 :(得分:1)

如果您想在连接表中使用其他属性,可以在定义关联之前在sequelize中为连接表定义模型,然后告诉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

访问连接表属性:

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