多对多: 学生和老师,一个老师有多个学生,一个学生有多个老师
要确定某条数据需要同时确定学生和老师的关系
一般需要第三张表进行记录,比如把某个学生的id和某个老师的id组合当成一行数据记录,来确定
以下代码进行简写
Student.associate = function (){
// 与Teacher存在多对多关系,使用belongsToMany()
app.model.Student.belongsToMany(app.model.Teacher, {
// 通过TeacherStudent模型对应的表查询
// foreignKey和Student匹配的值,再匹配otherKey的值
// 例如: student表的id和TeacherStudent表的studentId匹配上了
// 然后得到teacherId去和teacher表匹配得到的结果就是这个id的学生的老师
through: app.model.TeacherStudent,
// 注意驼峰还是下划线,
// 模型配置里面underscored默认为true,把驼峰转换为下划线
foreignKey: 'studentId', //这两个字段是主键或者是外键类型和两张表对应
otherKey: 'teacherId'
});
}
return Student;
Teacher.associate = function(){
app.model.Teacher.belongsToMany(app.model.Student, {
through: app.model.TeacherStudent,
foreignKey: 'teacherId',
otherKey: 'studentId'
});
}
return Teacher;
TeacherStudent.associate = function(){}
return TeacherStudent;
// contro.js
async info(){
const { ctx, app } = this;
//学生有哪些老师
let result = await app.m.Student.findAll({
include: {
model: app.m.Teacher
}
});
ctx.body = result;
// 每个老师有哪些学生
// let result = await app.m.Teacher.findAll({
// include: {
// model: app.m.Student
// }
// });
// ctx.body = result;
}
总结:
多对多是固定的格式
表一模型.belongsToMany(表二模型, {
through: 中间表模型,
foreignKey: '在中间表里面和表一匹配的字段',
otherKey: '在中间表里面和表二匹配的字段'
});
查询还是
await app.m.Student.findAll({
include: {
model: app.m.Teacher
}
});