4つのテーブルを関連付けようとしています。タスク、TaskQuestions、質問とオプション。Sequelize - 4つのテーブルを関連付ける
タスクモデルを次のように私のモデルは以下のとおりです。
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var Task = sequelize.define('Task', {
task_id: {
type: Sequelize.STRING,
primaryKey: true
},
task_name: {
type: Sequelize.STRING,
allowNull: true
},
task_description: {
type: Sequelize.STRING,
allowNull: true
}
},{
classMethods: {
associate: function(models) {
Task.belongsToMany(models.Question, {
through: {
model: models.TaskQuestion
},
foreignKey: 'task_id'
})
}
}
});
return Task;
};
TaskQuestionsモデル:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var TaskQuestion = sequelize.define('TaskQuestion', {
tq_id: {
type: Sequelize.STRING,
primaryKey: true
}
});
return TaskQuestion;
};
質問モデル:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var Question = sequelize.define('Question', {
question_id: {
type: Sequelize.STRING,
primaryKey: true
},
question_description: {
type: Sequelize.STRING,
allowNull: true
},
question_type: {
type: Sequelize.STRING,
allowNull: true
}
},{
classMethods: {
associate: function(models) {
Question.hasMany(models.Option, {
foreignKey: {
name: 'question_id',
allowNull: false
}
}),
Question.belongsToMany(models.Task, {
through: {
model: models.TaskQuestion
},
foreignKey: 'question_id'
})
}
}
});
return Question;
};
オプションモデル:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var Option = sequelize.define('Option', {
option_id: {
type: Sequelize.STRING,
primaryKey: true
},
question_id: {
type: Sequelize.STRING,
allowNull: true
},
option_description: {
type: Sequelize.STRING,
allowNull: true
},
option_type: {
type: Sequelize.STRING,
allowNull: true
}
},{
classMethods: {
}
});
return Option;
};
私はデータ
router.get('/:task_id', function(req, res) {
models.Task.findOne({
where: {
task_id: req.params.task_id
},
include: [ models.Question ]
}).then(function(task) {
res.json(task);
});
});
を取得しようとすると、私が得るすべてのタスクと質問の間の関連です。質問を個別に取り出すと、その下にオプションが表示されます。しかし、一度にすべてを取得するように見えることはできません。
でも可能ですか?この形式でデータベースを設計する正しいアプローチに従っているかどうかを教えてください。
複数の質問を含めるには1つのタスクが必要で、複数のタスクで同じ質問が表示されることがあります。それぞれの質問には複数のオプションを含める必要があります。
それが働いた:上記のご例えば
include
さんネストされた、このようなものは、トリックを行う必要があります。どうもありがとう。 :) –