2016-08-02 45 views
2

是否可以通過through包含多對多關係屬性的模型?續集:包含through.attribute的模型

比方說,我有以下型號:

User = sequelize.define('user', {/* attributes */}); 
Question = sequelize.define('question', {/* attributes */}); 
Answer = sequelize.define('answer', {/* attributes */}); 

/* Where */ 
Question.hasMany(Answer); 
Answer.belongsTo(Question); 

我想保存這回答他給了一個問題每一個用戶。因此,我增加了以下關係:

UserQuestionAnswerRel = sequelize.define('usersAnwers', { 
    user: {/**/}, 
    question: {/**/}, 
    answer: {/**/} 
}); 

User.hasMany(Question, { through: UserQuestionAnswerRel }); 

現在我想查詢用戶接收他回答所有的問題,他給了答案。但這是如何工作的?不幸的是,這並不工作:

User.findAll({ 
    include: { 
    model: Question, 
    through: { include: model.Answer } 
    } 
}).then /* */ 

請注意:所有這種問答&一個東西,僅僅是一個例子。我不可能不使用through關係。

+0

有趣。對不起,我還沒有答案。但不知道它是否與我的問題類似。 http://stackoverflow.com/questions/38714624/with-sequelize-pre-filter-a-results-set-based-on-custom-attribute我essentually想訪問'通過'模型和篩選記錄遺漏'內部'加入 – JAG

+0

你能解釋爲什麼你必須使用'through'嗎?這應該是非常簡單的[嵌套預先加載](http://sequelize.readthedocs.io/en/latest/docs/models-usage/index.html#nested-eager-loading)... – Will

回答

3

我想查詢用戶接收他回答所有的問題,他給了

您應該使用Nested eager loading答案。因此,例如,您的查詢可能類似於:

User.findAll({ 
    include: { 
    model: UserQuestionAnswerRel, 
    include: [ 
     { model: Question }, 
     { model: Answer } 
    ] 
    } 
}).then...