我有两个n:m续集模型,如下所示
// 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.
}
注意:多个组织可以连接多个联系人。在联系人之前创建组织。
基于this文档,在我尝试
后保存联系人Organization.addContact(contact);
我得到一个例外
Organization.addContact is not a function
答案 0 :(得分:2)
addContact
方法应该在Organization
的实例上调用,而不是在模型本身上调用,就像在示例代码中一样。
Organization.create(organizationData).then(organization => {
organization.addContact(contact).then(() => {
// contact was added to previously created organization
});
});
您的联系人创建数据中不需要organizationId
属性。如果要使用id: 1
向组织添加新联系人,则首先需要返回组织实例,然后执行addContact
方法
Organization.findByPrimary(1).then(organization => {
organization.addContact(contact).then(() => {
// contact was added to organization with id = 1
});
});