简体   繁体   English

Sequelize EmiratesToMany关联无效

[英]Sequelize belongsToMany association is not working

My workbook is 我的workbook

Workbook = sequelize.define('Workbook', {
    isAssessment: {
      type: DataTypes.BOOLEAN,
      allowNull: false
    },
    originalId: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Workbook.belongsTo(models.Student);
        Workbook.belongsTo(models.Subject);
        return Workbook.belongsToMany(models.Question, {
          through: models.GradedWorkbook
        });
      }
    }
  });

I have another model: 我有另一个模型:

GradedWorkbook = sequelize.define('GradedWorkbook', {}, {
  classMethods: {
    associate: function(models) {
      GradedWorkbook.belongsTo(models.Answer, {
        as: 'AnswerA'
      });
      GradedWorkbook.belongsTo(models.Answer, {
        as: 'AnswerB'
      });
      GradedWorkbook.belongsTo(models.Answer, {
        as: 'AnswerC'
      });
      GradedWorkbook.belongsTo(models.Answer, {
        as: 'AnswerD'
      });
      return GradedWorkbook.belongsTo(models.Answer, {
        as: 'AnswerSelected'
      });
    }
  }
});

And the third model 第三种模式

Question = sequelize.define('Question', {
  active: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  flagged: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  questionText: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  level: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  originalId: {
    type: DataTypes.STRING,
    allowNull: false
  }
}, {
  classMethods: {
    associate: function(models) {
      Question.hasMany(models.Answer);
      Question.belongsTo(models.Instruction);
      Question.belongsTo(models.Topic);
      Question.belongsTo(models.Subject);
      Question.belongsTo(models.Passage);
      return Question.belongsToMany(models.Workbook, {
        through: models.GradedWorkbook
      });
    }
  }
});

When I try to do a query: 当我尝试执行查询时:

newWorkbook = {
  isAssessment: icmVal.isAssessment || false,
  originalId: icmSnapshot.key()
};

db.Workbook.findOrCreate({
  where: newWorkbook,
  include: [db.GradedWorkbook],
  defaults: newWorkbook
}).spread(function(dbWorkbook) {
  return console.log(dbWorkbook);
});

I get an error: Unhandled rejection Error: GradedWorkbook is not associated to Workbook! 我收到一个错误: Unhandled rejection Error: GradedWorkbook is not associated to Workbook! . What am I doing incorrectly? 我做错了什么?

There is no direct association between Workbook and GradedWorkbook - it is only used as a through model. Workbook和GradedWorkbook之间没有直接关联-它仅用作直通模型。 You can only use direct associations, eg creating questions and workbooks together 您只能使用直接关联,例如,一起创建问题和工作簿

Workbook.findOrCreate({
  include: [db.Question]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM