未处理的拒绝SequelizeEagerLoadingError:Sequelize

时间:2018-10-10 16:02:53

标签: javascript node.js orm sequelize.js

这是我的模型:sensor.js

   'use strict';
    module.exports = (sequelize, DataTypes) => {
      const Sensor = sequelize.define('Sensor', {
        sensorName: DataTypes.STRING,
        user: DataTypes.INTEGER
      }, {});
      Sensor.associate = function(models) {
        Sensor.hasMany(models.User, {
            foreignKey: 'user'
        })
      };
      return Sensor;
    };

user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    User.belongsTo(models.Sensor, {
      foreignKey: 'user'
    })
  };
  return User;
};

在做

Sensor.findAll({
  'raw':true,
  include: [{
    model: User
  }]
})
.then(function(result){
  console.log(result)
})

我遇到以下错误:

  

未处理的拒绝SequelizeEagerLoadingError:用户未与Sensor关联!

1 个答案:

答案 0 :(得分:0)

您正在创建与对象关系同名的列(user),这很可能引起冲突。默认情况下,Sequelize将自动创建userId(或user_id,具体取决于设置)列,并且您无需在define()或关联中包括它,而您正在使用{{ 1}}为ID建立关系。

使用user属性来定义as关系,因为它们是复数形式。

sensor.js

1:n

user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Sensor = sequelize.define('Sensor', {
    sensorName: DataTypes.STRING,
  }, {});
  Sensor.associate = function(models) {
    Sensor.hasMany(models.User, { as: 'users' })
  };
  return Sensor;
};

查询

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    User.belongsTo(models.Sensor)
  };
  return User;
};