我正在将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
文件,其中包含这两个实体之间的关联 .
什么会???初始化程序中的部分和样本关联文件看起来像?
1 回答
我最终使用下面的方法,因为它保持与它相关的对象(和文件)的关联 . 例如,当Party.js文件中的Party模型打开时,可以看到列和任何关系 .
在ActionHero的初始化程序中,我首先通过Sequelize的import()加载模型,然后迭代所有加载的模型,并在每个模型上调用名为associate()的已知类方法(如果存在)以创建关联 .
这是一个模型的例子: