belongsTo - hasMany - 从belongsTo获取实例 - sequelize

时间:2016-07-06 12:03:48

标签: associations sequelize.js

如果我有以下型号:

module.exports = function (sequelize, DataTypes) {
  var WorkingCalendar = sequelize.define('WorkingCalendar', {
    date: DataTypes.DATEONLY,
    isWorking: DataTypes.BOOLEAN,
  }, {
      indexes: [{
        unique: true,
        fields: ['PeriodId', 'date']
      }]
    }, {
      classMethods: {
        associate: function (models) {
          WorkingCalendar.belongsTo(models.Period);
        }
      }
    });
  return WorkingCalendar;
};

module.exports = function(sequelize, DataTypes) {
  var Period = sequelize.define('Period', {
    name: DataTypes.STRING,
    numberOfPeriods: DataTypes.INTEGER
  }, {
    classMethods: {
      associate: function(models) {
        Period.hasMany(models.WorkingCalendar);
      }
    }
  });
  return Period;
};

然后尝试通过Period获取WorkingCalendar,如下所示:

return models.WorkingCalendar
.findAll({
    attributes: [
        'PeriodId',
        'date'
    ],
    include: [
        { model: models.Period }
    ],
    group: ['date', 'PeriodId']
});

我收到以下错误:未处理的拒绝错误:期间与WorkingCalendar没有关联!

然而它确实相反。

我的问题: 为什么我无法通过Period获得WorkingCalendar?我需要做些什么来确保我能做到?

我已经尝试将foreignKey属性放在关联上以及as绑定,但遗憾的是无济于事。非常欢迎任何帮助!

1 个答案:

答案 0 :(得分:1)

所以终于找到了它。 indexes应与classMethods

位于同一对象中

<强> WRONG

module.exports = function (sequelize, DataTypes) {
 var WorkingCalendar = sequelize.define('WorkingCalendar', {
    date: DataTypes.DATEONLY,
    isWorking: DataTypes.BOOLEAN,
  }, {
      indexes: [{
        unique: true,
        fields: ['PeriodId', 'date']
      }]
    }, {
      classMethods: {
        associate: function (models) {
          WorkingCalendar.belongsTo(models.Period);
        }
      }
    });
  return WorkingCalendar;
};

从右

module.exports = function (sequelize, DataTypes) {
  var WorkingCalendar = sequelize.define('WorkingCalendar', {
    date: DataTypes.DATEONLY,
    isWorking: DataTypes.BOOLEAN,
  }, {
      indexes: [{
        unique: true,
        fields: ['PeriodId', 'date']
      }],
      classMethods: {
        associate: function (models) {
          WorkingCalendar.belongsTo(models.Period);
        }
      }
    });
  return WorkingCalendar;
};