续集多对多关联 – 未find方法

我有两个n:m sequelize模型,如下所示

// Organization Model module.exports = { attributes: { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: Sequelize.STRING, required: true }, }, associations: function() { Organization.belongsToMany(Contact, { through : OrganizationContact, foreignKey: { name: 'organizationId', allowNull: false } }); } }; // OrganizationContact Model module.exports = { attributes: { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } } } // Contact Model module.exports = { attributes: { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, firstname: { type: Sequelize.STRING, required: true }, lastname: { type: Sequelize.STRING, required: false }, }, associations: function() { Contact.belongsToMany(Organization, { through : OrganizationContact, foreignKey: { name: 'contactId', allowNull: false } }); } }; 

我正在尝试插入联系人并将其附加到现有组织。 我的数据看起来像

 { "firstname" : "Mathew", "lastname" : "Brown", "organizationId" : 1 // Add the contact to an existing organization. I am missing something here. } 

注意:可以有多个联系人连接到多个组织。 联系人之前创build一个组织。

根据这个文档,当我尝试保存联系人后

 Organization.addContact(contact); 

我得到一个exception说

 Organization.addContact is not a function 

addContact方法应该在Organization实例上而不是模型本身上调用,就像在示例代码中一样。

 Organization.create(organizationData).then(organization => { organization.addContact(contact).then(() => { // contact was added to previously created organization }); }); 

您不需要联系人中的organizationId属性创build数据。 如果要将新联系人添加到id: 1的组织中,则首先需要返回组织实例,然后执行addContact方法

 Organization.findByPrimary(1).then(organization => { organization.addContact(contact).then(() => { // contact was added to organization with id = 1 }); });