在Sequelize中加载关联

时间:2015-02-25 15:51:04

标签: node.js associations sequelize.js

我正在将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 个答案:

答案 0 :(得分:3)

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

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

// 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'});
      }
    }
  }
)