2016-08-25 59 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' 
    } 
    } 
] 
相關問題