如何在sequelize中获得一组模型关联

时间:2016-08-25 06:51:09

标签: node.js sequelize.js

这是Buildings

的模型
var Buildings = sequelize.define('buildings', buildingsDefinition,
    {
        timestamps: true,
        underscored: false,
        paranoid: true,
        indexes: [
            { fields: ['accId']}
        ],
        engine: 'innodb',
        classMethods:{
            associate:function(models){
                this.hasMany(models.Rooms, {
                    as: 'Rooms',
                    foreignKey: 'buildingId',
                    onUpdate: 'NO ACTION',
                    onDelete: 'NO ACTION',
                    constraints: false
                })
            }
        }
    }
);

在路线中,如何获得此模型的关联数组?

期望的结果,如:

[
    {'Rooms':
        {
            as: 'Rooms',
            foreignKey: 'buildingId',
            onUpdate: 'NO ACTION',
            onDelete: 'NO ACTION',
            constraints: false
        }
    }
]

Models.Buildings.classMethods

这样的东西

1 个答案:

答案 0 :(得分:5)

Sequelize模型没有将关联列为数组的方法。但由于模型包含有关关联和关联选项的信息,我们可以解析这些选项以获得所需的结果。

将模型对象传递给粗略函数,如下所示:

function modelAssociationsToArray(model) {
  const result = [];

  if (typeof model !== 'object' || typeof model.associations !== 'object') {
    throw new Error("Model should be an object with the 'associations' property.");
  }

  Object.keys(model.associations).forEach((key) => {
    const association = {};

    // all needed information in the 'options' object
    if (model.associations[key].hasOwnProperty('options')) {
      association[key] = model.associations[key].options;
    }

    result.push(association);
  });

  return result;
}

我们可以获得与此类似的关联列表:

[
  { 
    Product: { 
      foreignKey: [Object],
      onDelete: 'restrict',
      hooks: {},
      useHooks: false,
      timestamps: true,
      ...
      hasPrimaryKeys: true,
      onUpdate: 'CASCADE'
    }
  },
  { 
    User: { 
      foreignKey: [Object],
      onDelete: 'restrict',
      hooks: {},
      useHooks: false,
      timestamps: true,
      ...
      hasPrimaryKeys: true,
      onUpdate: 'CASCADE'
    }
  }
]