0
我在兩個模型之間有多對多關聯Hospital
和Contact
。在聯繫人記錄中添加,但在關聯表hospitals_contacts
中沒有條目。 sequelize生成外鍵contact_id和hospital_id作爲組合主鍵。續集多對多關聯連接表不填充
接觸模型
module.exports = function(sequelize, DataTypes) {
var Contact = sequelize.define("Contact", {
job_title: DataTypes.STRING,
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
archived: DataTypes.BOOLEAN,
primary_email: {
type: DataTypes.STRING,
validate: {
isEmail: true
}
},
business_number: DataTypes.STRING,
number_extension: DataTypes.STRING,
fax_number: DataTypes.STRING
}, {
underscored:'true',
tableName: 'contacts',
createdAt: false,
updatedAt: false,
classMethods: {
associate: function(models) {
Contact.belongsToMany(models.Hospital, { through: 'hospitals_contacts'});
Contact.belongsTo(models.Type);
Contact.belongsTo(models.Region)
}
},
});
return Contact;
};
醫院模式
module.exports = function(sequelize, DataTypes) {
var Hospital = sequelize.define("Hospital", {
name: DataTypes.STRING,
mak_code: DataTypes.STRING,
licensed_tm_lab: DataTypes.BOOLEAN
}, {
underscored:'true',
tableName: 'hospitals',
createdAt: false,
updatedAt: false,
classMethods: {
associate: function(models) {
Hospital.belongsToMany(models.Contact, { through: 'HospitalsContacts'});
Hospital.belongsTo(models.Address)
}
}
});
return Hospital;
};
API端點添加聯繫人
var hospitalInstance = models.Hospital;
var contactData = req.body;
models.Contact.create({
first_name: contactData.first_name,
last_name: contactData.last_name,
type_id: contactData.type,
job_title: contactData.job_title,
primary_email: contactData.email,
business_number:contactData.phone_number,
fax_number:contactData.fax,
number_extension:contactData.extension,
region_id: contactData.region,
committee_id: contactData.committee,
archived: false,
hospitalInstance: {id:contactData.hospital}
},
{
include: [hospitalInstance]
});