gpt4 book ai didi

javascript - 继承多对多关联 - 找不到方法

转载 作者:行者123 更新时间:2023-11-30 15:26:50 26 4
gpt4 key购买 nike

我有两个 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.
}

注意:可以有多个联系人附加到多个组织。组织先于联系人创建。

基于 this文档,在我尝试保存联系人后

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 属性。如果要向id: 1的组织添加新的联系人,那么首先需要返回组织实例,然后执行addContact方法

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

关于javascript - 继承多对多关联 - 找不到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com