续集多对多关联 - 未找到方法

时间:2017-03-16 06:20:29

标签: javascript node.js orm sails.js sequelize.js

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

1 个答案:

答案 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
    });
});