2016-08-25 71 views
2

这是我Buildings如何获得模型关联数组中sequelize

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

回答

4

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' 
    } 
    } 
] 
相关问题