为每个模型创建一个像这样的文件:Car.js, City.js
然后在每个模型中你这样做:
module.exports.getModel = function(sequelize){sequelize.define("Car"...)}
module.exports.setAssociations(models){models.Car.hasOne(models.City)}
要做到这一点,你想抽象出这样的方式:
var sequelize = this.__connection;
var Sequelize = require('sequelize');
var rootFolder = this.__rootFolder;
var modelsNames = this.getModelsNames(rootFolder);
var i = k = modelsNames.length;
var modelName;
var models = {};
var modelFactoryFn;
// load models
while(i--){
modelName = modelsNames[i];
var Model = require(path.resolve(rootFolder, modelName)).getModel(sequelize);
if(!Model){
throw new Error("No model returned from " + path.resolve(rootFolder, modelName));
}
models[modelName] = Model;
}
// build associations
var modelFile;
while(k--){
modelName = modelsNames[k];
modelFile = require(path.resolve(rootFolder, modelName));
if(modelFile.buildAssociations){
modelFile.buildAssociations(models);
}
}
this.__models = models;
我知道这可能会更好,但这可以让你现在就开始工作,并且比用文字更好地解释。