如何获得多个连接的结果

时间:2016-01-20 03:59:44

标签: sequelize.js

我有以下设置:

...
Survey.hasMany(Question, {as: 'Questions'});
Question.hasMany(Answer, {as: 'Answers'});

如何获得单个调查的完整记录集?我知道如何获得调查的所有问题,但我希望每个问题都能得到与之相关的所有答案。

Question.findAll({
  where: {
    surveyId: req.surveyId
  }
}).then(function (questions) {
  // Now how do I join questions with their answers?
}, function (err) {

});

我理想的结构是:

var survey = [
  {
    question: 'some question',
    answers: [{...},{...},...]
  }, 
  {
    ...
  },
  .
  .
  .
]

1 个答案:

答案 0 :(得分:2)

您应该包含相关模型。

Question.findAll({
    where: {
        surveyId: req.surveyId
    },
    include: [{
        model: Answer,
        as: 'Answers'
    }]
}).then(function (questions) {
    console.log(questions[0].Answers);
}, function (err) {

});

或者您可以查询Survey模型并同时包含QuestionAnswer

Survery.findAll({
    where: {
        id: req.surveyId
    },
    include: {
        model: Question,
        include: {
            model: Answer
        }
    }
}).then(function (surveys) {
    console.log(surveys[0]);
}, function (err) {

});