对findOne-includes进行排序:缺少联接表ID

时间:2019-05-20 17:37:38

标签: many-to-many sequelize.js

我想用包含连接表的学生查询一个主题。 这种关系是多对多的。我想要连接表ID(StudentSubject),但返回结果为空

Subject.findOne({
            where:{id},
            include: [
                { model: Student, attribute: ['id', 'name']},
                { model: StudentSubject, attribute: ['id', 'subject', 'student', 'score'], as: "studentSubject"}
            ]
        })

关系如下

学生

Student.belongsToMany(models.Subject, { through: models.StudentSubject, foreignKey: 'student'})
Student.belongsTo(models.StudentSubject, {foreignKey: 'id', targetKey: 'student', as: 'studentSubject'})

主题

Subject.belongsToMany(models.Student, { through: models.StudentSubject, foreignKey: 'subject'})
Subject.belongsTo(models.StudentSubject, { foreignKey: 'id', targetKey: 'subject', as: 'studentSubject'})

联接表模型

// it has id by default in the migration file
const StudentSubject = sequelize.define('StudentSubject', {
    student: DataTypes.INTEGER,
    subject: DataTypes.INTEGER,
    score: DataTypes.INTEGER
  }

结果缺少连接表ID,我在这里想念什么?

enter image description here

其他实验

也尝试了在学生中嵌套包含,这不起作用。它也没有ID

Subject.findOne({
            where:{id},
            include: [
                { model: Student, attribute: ['id', 'name'], include: [
                    { model: StudentSubject, attribute: ['id', 'subject', 'student', 'score'], as: "studentSubject"}
                ]},
            ]
        })

2 个答案:

答案 0 :(得分:0)

我还没有对此进行测试,但是您可能需要在第一个代码块中包含id表的Subject。以下可能会为您提供所需的信息。

Subject.findOne({
        where:{id},
        include: [
            { model: Subject, attribute: ['id']},
            { model: Student, attribute: ['id', 'name']},
            { model: StudentSubject, attribute: ['id', 'subject', 'student', 'score'], as: "studentSubject"}
        ]
    })

答案 1 :(得分:0)

原来,我必须在连接表模型中定义ID。我以为不是,所以在这里

sequelize.define('StudentSubject', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    student: DataTypes.INTEGER,
    subject: DataTypes.INTEGER,
    score: DataTypes.INTEGER
  }

我错误地定义了关联,所以我来到了

Student.hasMany(models.StudentSubject, {foreignKey: 'student'})
Subject.hasMany(models.StudentSubject, { foreignKey: 'subject'})
StudentSubject.belongsTo(models.Student, {foreignKey: 'student', sourceKey: 'id'})
StudentSubject.belongsTo(models.Subject, {foreignKey: 'subject', sourceKey: 'id'})

,现在使用

查询时
Subject.findOne({
            where:{id},
            include: [
                { model: Student, attribute: ['id', 'name'], include: [
                    { model: StudentSubject, attribute: ['id', 'subject', 'student', 'score'], as: "studentSubject"}
                ]},
            ]
        })

现在可以使用