Sequelize与Postgresql中的一对多关联

时间:2016-08-03 22:11:18

标签: javascript sequelize.js

每当我尝试在Postgresql支持的Sequelize中创建1:多关联时,我都会收到此错误。

  

未处理拒绝错误:ProbeProfile未与Profile关联!

个人资料模型定义:

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Profile = sequelize.define('Profile', {
    id: { type: DataTypes.INTEGER, primaryKey: true},
    name: DataTypes.STRING,
    description: DataTypes.TEXT,
    isDeleted: DataTypes.BOOLEAN,
    createdAt: DataTypes.DATE,
    updatedAt: DataTypes.DATE          
  }, {
    tableName: 'profiles',
    classMethods: {
      associate: function(models) {
        Profile.hasMany(models.ProbeProfile, { as: 'ProbeProfiles' });
      }
    }
  });

  return Profile;
};

ProbeProfile模型定义:

'use strict';

module.exports = function(sequelize, DataTypes) {
  var ProbeProfile = sequelize.define('ProbeProfile', {
    id: { type: DataTypes.INTEGER, primaryKey: true},
    label: DataTypes.STRING,
    upperThreshold: DataTypes.INTEGER,
    lowerThreshold: DataTypes.INTEGER,
    probeChannel: DataTypes.INTEGER,
    profileId : DataTypes.INTEGER,
    readingDateTime: DataTypes.DATE
  }, {
    classMethods: {
      associate: function(models) {
        ProbeProfile.belongsTo(models.Profile, { foreignKey: 'profileId' });
      }
    }
  });

  return ProbeProfile;
};

最后,我正在使用的查询:

models.Profile.findAll({ where: { id: id },  include: [models.ProbeProfile] }).then(function(rows) {
        cb(rows);
    });

基于我在SO和Sequelize Express示例中看到的内容,我不确定为什么会收到此错误。

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是由于在Profile模型定义中使用'as:ProbeProfiles'。为了使查询起作用,它还包含'as'。

models.Profile.findAll({ where: { id: id },  include: [{ model: models.ProbeProfile, as: 'ProbeProfiles' }] }).then(function(rows) {
        cb(rows);
    });
相关问题