我正在尝试使用sequelize来获得关联。
我在这里有3个具有属性的模型:
生 id,name,class等
student_details studentId,subjectId
受试者 id,subject
我想获得学生的所有科目名称,我不想直接将这些信息存储在学生表中。有解决方法吗?
协会是:
模型/ Student.js
classMethods: {
associate: (models) => {
Students.studentDetails = Students.hasOne(models.f_student_details, { foreignKey: { name: 'studentId', allowNull: false }, as: 'studentDetails' });
}
}
模型/ StudentDetails.js
classMethods: {
associate: (models) => {
StudentDetails.belongsTo(models.subjects, { foreignKey: { name: 'subjectId', allowNull: true }, through: 'subjects' });
}
模型/ Subjects.js
classMethods: {
associate: (models) => {
Subjects.hasOne(models.student_details, { foreignKey: { name: 'subjectId', allowNull: false }, as: 'studentSubject' });
}
方法调用:
db.students.findAll({
include: [ model: db.students]
})
现在,它只返回studentDetails。我想通过学生对象中的学生详细信息来学习科目。只是提出问题!
答案 0 :(得分:1)
你应该使用这样的嵌套包含:
Students.findAll({
include: {
model: db.studentDetails,
include: [ db.subjects ]
}
});
但是,您需要从以下模型中删除“as”键:
模型/ students.js
classMethods: {
associate: (models) => {
Students.studentDetails = Students.hasOne(models.f_student_details, { foreignKey: { name: 'studentId', allowNull: false } });
}
模型/ subjects.js
classMethods: {
associate: (models) => {
Subjects.hasOne(models.student_details, { foreignKey: { name: 'subjectId', allowNull: false } });
}
}
模型/ studentDetails.js
classMethods: {
associate: (models) => {
StudentDetails.belongsTo(models.subjects, { foreignKey: { name: 'subjectId', allowNull: true } });
}
检查此stackoverflow post