2017-03-16 58 views
1

我有兩個N:M sequelize模型如下圖所示Sequelize許多-to-many關聯 - 找不到方法

// 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

你是如何命名的車型('sequelize.define'方法的第一個參數)? – piotrbienias

+0

我正在使用sails-sequelize-hook。 –

回答

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 
    }); 
}); 
+0

你救了我的一天! –