简体   繁体   English

Sequelize:包含 through.attribute 的模型

[英]Sequelize: Include model of through.attribute

Is it possible to include a model for an attribute of a many-to-many relation via through ?是否可以通过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.我不可能不使用through关系。

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...

I think the way to look at this question is:我认为看待这个问题的方式是:

`User.hasMany(Question); //this gives every question a userId
 Question.belongsTo(User);
 User.hasMany(Answer); //this gives every answer a userId
 Answer.belongsTo(User);
 Question.hasMany(Answer); //this gives every answer a questionId
 Answer.beongsTo(Question);

` `

So, a query to get a user receiving all questions he answered and the answer he gave would go like this:因此,让用户收到他回答的所有问题以及他给出的答案的查询将如下所示:

 `User.findAll({
  where: {
     id: userId
   },
   include: [
    { model: Answer },
       include: [
       { model: Question }
       ]
     ]
    });

` `

This query is selecting a user with a supplier ID (userId) from the users table, and including all answers belong to that user, and also including all questions belonging to each of the answers included.此查询从用户表中选择具有供应商 ID (userId) 的用户,并且包括属于该用户的所有答案,还包括属于所包含的每个答案的所有问题。

Let me know when you try this当你尝试这个时告诉我

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

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