本文介紹了從多個表中選擇封存的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我目前正在開發一個使用Sequelize的系統,我需要一個從多個表中獲取數據的查詢,如下所示:
Select Courses.id, Rooms.DisplayLabel, Periods.DisplayName, Subjects.Name
from Rooms, Periods,Subjects, Courses
where Periods.id = Courses.PeriodId and Rooms.id=Courses.RoomId
and Subjects.id = Courses.SubjectId and Courses.id = 2
房間、主題和時段是目錄,課程是我保存所有鑰匙的表。序列化定義如下:
module.exports = function(sequelize, DataTypes) {
var Course = sequelize.define('Course', {
Scholarship: {
type: DataTypes.STRING(30)
},
Level: {
type: DataTypes.INTEGER(2),
},
CourseType: {
type: DataTypes.STRING(30),
},
RecordStatus: {
type: DataTypes.BOOLEAN,
default: true
},
DeletedAt: {
type: DataTypes.DATE
}
},
{
associate: function(models){
Course.belongsTo(models.School, {foreignKey: {unique: true}});
Course.belongsTo(models.Person, {foreignKey: {unique: true}});
Course.belongsTo(models.Period, {foreignKey: {unique: true}});
Course.belongsTo(models.Schedule, {foreignKey: {unique: true}});
Course.belongsTo(models.Room, {foreignKey: {unique: true}});
Course.belongsTo(models.Subject, {foreignKey: {unique: true}});
Course.belongsTo(models.user, { as: 'CreatedBy' });
Course.belongsTo(models.user, { as: 'UpdateBy' });
Course.belongsTo(models.user, { as: 'DeleteBy' });
}
}
);
return Course;
};
到目前為止,我在我的控制器上得到的唯一查詢是:
exports.courseFields = function(req, res) {
db.Course.find({
where: {id: req.params.PeriodIdF},
attributes: ['id'],
include: [{model:db.Room, attributes:['DisplayLabel']}]})
.then(function(courses) {
return res.json(courses);
})
.catch(function(err) {
return res.render('error', {
error: err,
status: 500
});
});
};
我的問題是,如何包括其他表和字段?我搞不懂Sequelize的工作原理。
推薦答案
更新您的包含阻止
include: [
{model:db.Room, attributes:['DisplayLabel']},
{model:db.Periods, attributes:['DisplayLabel']},
{model:db.Subjects, attributes:['Name']}
]
這篇關于從多個表中選擇封存的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,