未处理的拒绝SequelizeEagerLoadingError:未关联,并且无法读取未定义的属性'getTableName'

时间:2018-09-03 16:28:54

标签: node.js orm sequelize.js

我有3个表:User,Trip,authoriseDate。 这是同事: 用户有多次旅行,而用户有一个authorizeDate 用户一对多旅行 用户一对一授权日期 这是模型 用户

 module.exports = (sequelize, DataTypes) => {
  const user = sequelize.define('User', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    email: { type: DataTypes.STRING(50), unique: true },
    phoneNumber: {
      type: DataTypes.STRING(12), unique: true,
    },
  }, {
    classMethods: {
      associate(models) {
        // associations can be defined here
        user.hasOne(models.authoriseDate, { foreignKey: 'userId' });
        user.hasMany(models.Trip, { foreignKey: 'userId' });
      },
    },
  });
  return user;
};

旅行

module.exports = (sequelize, DataTypes) => {
  const trip = sequelize.define('Trip', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    userId: DataTypes.INTEGER,
    status: DataTypes.INTEGER,
  }, {
    classMethods: {
      associate(models) {
        // associations can be defined here
        trip.belongsTo(models.User, { foreignKey: 'userId' });
      },
    },
  });
  return trip;
};

authoriseDate

module.exports = (sequelize, DataTypes) => {
  const authoriseDate = sequelize.define('AuthoriseDate', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    userId: DataTypes.INTEGER,
    lastAuthorise: DataTypes.DATE,
  }, {
    classMethods: {
      associate(models) {
        // associations can be defined here
        authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });
      },
    },
  });
  return authoriseDate;
};

但是当我使用findAll函数

models.User.findAll({
    include: [{
      model: models.Trip,
    },
    {
      model: models.authoriseDate,
    }],
  })

这是我的模型文件

    'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
//var env = process.env.NODE_ENV || 'development';
//var config    = require(__dirname + './../../../config/config.json')[env];
var config = require('../../config/env')
var db = {};

// if (config.use_env_variable) {
//   var sequelize = new Sequelize(process.env[config.use_env_variable]);
// } else {
//   var sequelize = new Sequelize(config.database, config.username, config.password, config);
// }

var sequelize = new Sequelize(config.dbName, config.dbUserName, config.dbPassword, {
  host: config.dbHost,
  dialect: config.dbDialect,
});

fs
  .readdirSync(__dirname)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function (file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

我遇到了错误: 未处理的拒绝SequelizeEagerLoadingError:行程未与用户关联,并且无法读取未定义的属性'getTableName' 我不知道如何解决这些错误,请任何人帮助我

1 个答案:

答案 0 :(得分:1)

您需要调用函数关联。

示例:

AuthoriseDate模型

module.exports = (sequelize, DataTypes) => {
    const authoriseDate = sequelize.define('AuthoriseDate', {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        userId: DataTypes.INTEGER,
        lastAuthorise: DataTypes.DATE,
    });

    authoriseDate.associate = (models) => {
        // associations can be defined here
        authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });
    };


    return authoriseDate;
};

旅行模式

module.exports = (sequelize, DataTypes) => {
    const trip = sequelize.define('Trip', {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        userId: DataTypes.INTEGER,
        status: DataTypes.INTEGER,
    });

    trip.associate = (models) => {
        // associations can be defined here
        trip.belongsTo(models.User, { foreignKey: 'userId' });
    };

    return trip;
};

用户模型

module.exports = (sequelize, DataTypes) => {
    const user = sequelize.define('User', {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        email: { type: DataTypes.STRING(50), unique: true },
        phoneNumber: {
            type: DataTypes.STRING(12), unique: true,
        },
    });

    user.associate = (models) => {
        // associations can be defined here
        user.hasOne(models.AuthoriseDate, { foreignKey: 'userId' });
        user.hasMany(models.Trip, { foreignKey: 'userId' });
    };


    return user;
};

初始化模型

'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
//var env = process.env.NODE_ENV || 'development';
//var config    = require(__dirname + './../../../config/config.json')[env];
// var config = require('../../config/env')
var db = {};

var sequelize = new Sequelize('test_01', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql',
});

fs
    .readdirSync(__dirname)
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== basename);
    })
    .forEach(function (file) {
        if (file.slice(-3) !== '.js') return;
        var model = sequelize['import'](path.join(__dirname, file));
        db[model.name] = model;
    });

console.log(db);

Object.keys(db).forEach((modelName) => {
    if (db[modelName].associate) {
        db[modelName].associate(db);
    }
});

(async () => {
    await sequelize.sync();
})();

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

使用查找

(async () => {
    const models = require('./models');

    const users = await models.User.findAll({
        include: [
            {
                model: models.Trip,
            },
            {
                model: models.AuthoriseDate,
            },
        ],
    });

    console.log(users);
})();

http://docs.sequelizejs.com/manual/tutorial/associations.html