Sequelize belongsToMany协会无效

时间:2016-02-20 19:53:57

标签: javascript node.js sequelize.js

我的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
        });
      }
    }
  });

我有另一种模式:

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'
      });
    }
  }
});

第三个模型

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
      });
    }
  }
});

当我尝试进行查询时:

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);
});

我收到错误:Unhandled rejection Error: GradedWorkbook is not associated to Workbook!。我做错了什么?

1 个答案:

答案 0 :(得分:1)

Workbook和GradedWorkbook之间没有直接关联 - 它仅用作直通模型。您只能使用直接关联,例如一起创建问题和工作簿

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