在Sequelize中加载关联

我将Sequelize整合到ActionHero中。 我的初始化程序执行以下操作:

// configure the singleton api.sequelize.sequelize = new Sequelize( api.config.sequelize.database, api.config.sequelize.username, api.config.sequelize.password, api.config.sequelize ); // import models var dir = path.normalize(api.projectRoot + '/models'); fs.readdirSync(dir).forEach(function(file){ var nameParts = file.split("/"); var name = nameParts[(nameParts.length - 1)].split(".")[0]; api.models[name] = api.sequelize.sequelize.import(dir + '/' + file); }); // import associations var dir = path.normalize(api.projectRoot + '/models/associations'); // ??? 

以下是/ models中的一个文件中的示例模型:

 module.exports = function(sequelize, DataTypes) { return sequelize.define( "Party", { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING(256), allowNull: false, unique: true, comment: "The legal name for the Party." }, dbaName: { type: DataTypes.STRING(256), comment: "The 'does business as' name for the Party." } }, { comment: "A Party is a person or group of persons composing a single entity with one or more roles in the system." } ) } 

不知道如何在Sequelize中定义和加载关联。 我希望将它们放在单独的文件中,并在加载所有模型后加载,以将它们绑定在一起。 例如,将会有一个PartyOperator.js文件包含这两个实体之间的关联。

什么? 初始化器中的一节和一个样例关联文件看起来像?

我结束了使用下面的方法,因为它保持与它相关的对象(和文件)的关联。 例如,当打开Party.js文件中的Party模型时,可以看到列和任何关系。

在ActionHero的初始化程序中,我首先通过Sequelize的import()加载模型,然后遍历所有加载的模型,并在每个模型上调用名为associate()的已知类方法(如果存在)以创build关联。

 // import models var dir = path.normalize(api.projectRoot + '/models'); api.log('loading models found in ' + dir, 'info'); var files = readdir.readSync(dir, ['**.js']); files.forEach(function(file) { var pathArray = file.split('/'); var name = pathArray[(pathArray.length - 1)].split('.')[0]; api.log('importing models/' + file + ' as ' + name, 'info'); api.models[name] = api.sequelize.sequelize.import(dir + '/' + file); }); api.log('running associations', 'info'); api.lodash.forEach(api.models, function(val, key) { if(api.lodash.isFunction(val.associate)) { val.associate(api.models); } }); 

这是一个模型的例子:

 sequelize.define( "Party", { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING(256), allowNull: false, unique: true, comment: "The legal name for the Party." }, dbaName: { type: DataTypes.STRING(256), comment: "The 'does business as' name for the Party." } }, { comment: "A Party is a person or group of persons composing a single entity with one or more roles in the system.", classMethods: { associate: function(models) { models.Party.hasMany(models.Operator, {foreignKey: 'Party_operatorID'}); } } } )