2016-02-20 98 views
0

workbookSequelize belongsToMany協會工作不

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

Workbook和GradedWorkbook之間沒有直接關聯 - 它僅用作直通模型。您只能使用直接關聯,例如一起創建問題和工作簿

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

嗯。我如何從GradedWorkbook獲取信息?或添加到它。 – Shamoon

+0

當你這樣做時,例如'Workbook.getQuestions()',每個問題都有一個'GradedWorkbook'屬性,其中來自連接表的信息 –