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

 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;
};

授权日期
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:Trip 未与用户关联,并且无法读取未定义的 的属性“getTableName”
我不知道如何解决这些错误,请任何人帮助我

最佳答案

您需要调用一个函数关联。

例子:

授权日期模型

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

关于node.js - 未处理的拒绝 SequelizeEagerLoadingError : is not associated to, 和无法读取未定义的属性 'getTableName',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52153500/

10-11 08:16