2017-03-16 5 views
1

私は2つのn持っている:私は連絡先を挿入し、既存の組織に添付しようとしています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 
      } 
     }); 

    } 
}; 

下に示すように、m個のsequelizeモデル。複数の組織に接続された複数の連絡先が存在することができます:注

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

のように私のデータが見えます。組織は連絡先の前に作成されます。

thisドキュメントに基づいて、連絡先を保存した後、私は私が

Organization.addContact is not a function 
+0

を実行する必要があります)? – piotrbienias

+0

私はsails-sequelize-hookを使用しています。 –

答えて

2

言って例外を取得addContact方法はOrganizationのインスタンスではなく、上と呼ばれるべき

Organization.addContact(contact); 

をしようとしたときモデル自体を、サンプルコードと同じように扱います。

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

連絡先作成データにorganizationId属性は必要ありません。あなたはid: 1と組織に新しい連絡先を追加したい場合は、まず組織のインスタンスを返し、その後、あなたは( `sequelize.define`メソッドの最初のパラメータをモデルに名前を付けましたかaddContact方法に

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

あなたは私の一日を救った! –

関連する問題