在sequelize中创建包含3个外键且没有私有属性的表

时间:2017-03-17 06:17:02

标签: database sequelize.js

使用3个外键创建关系表的最佳方法是什么,没有个人属性。 我想创建一个关系表teacher_subject_allocation,其中包含subjectteachersection

subject.belongsToMany(teacher, {through: 'teacher_subject_allocation'})

teacher.belongsToMany(section, {through: 'teacher_subject_allocation'})

1 个答案:

答案 0 :(得分:0)

//main tables 
//(foreignKey contains field name in association table)
subject.hasOne(teacher_subject_allocation , { foreignKey: 'subject_id' });
teacher.hasOne(teacher_subject_allocation , { foreignKey: 'teacher_id' });
section.hasOne(teacher_subject_allocation , { foreignKey: 'section_id' });

//association table 
//(targetKey is PK of main table, foreignKey is field of current table)
teacher_subject_allocation.belongsTo(subject, { targetKey: 'id', foreignKey: 'subject_id' });
teacher_subject_allocation.belongsTo(teacher, { targetKey: 'id', foreignKey: 'teacher_id' });
teacher_subject_allocation.belongsTo(section, { targetKey: 'id', foreignKey: 'section_id' });