从多个表中选择Sequelize

时间:2017-03-01 01:31:23

标签: mysql node.js sequelize.js

我目前正在使用sequelize开发一个系统,我需要一个查询从这样的多个表中获取数据:

b == 2000

房间,主题和期间是目录,课程是我保存所有密钥的表格。 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;
};

我的问题是,如何包含其他表和字段?我混淆了sequelize如何运作。

1 个答案:

答案 0 :(得分:1)

更新您的include bloack

include: [
             {model:db.Room, attributes:['DisplayLabel']},
             {model:db.Periods, attributes:['DisplayLabel']},
             {model:db.Subjects, attributes:['Name']}

       ]