Friday, May 17, 2024
2
rated 0 times [  4] [ 2]  / answers: 1 / hits: 18158  / 8 Years ago, tue, august 2, 2016, 12:00:00

Is it possible to include a model for an attribute of a many-to-many relation via through?



Let's say I'm having the following Models:



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

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


I'd like to save for every user which answer he gave to a question. So I added the following relation:



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

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


Now I'd like to query a user receiving all questions he answered and the answer he gave. But how does that work? Unfortunately this doesn't work:



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


Please note: All this Q&A stuff is just an example. It won't be possible for me to not use a through relation.


More From » sequelize.js

 Answers
19

I'd like to query a user receiving all questions he answered and the answer he gave




You should use Nested eager loading. So for example, you query might be something like:



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

[#61173] Saturday, July 30, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;