Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of model associations in sequelize

This is my model for 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
                })
            }
        }
    }
);

In a route, how do I get an array of the associations for this model?

Desired result, something like:

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

Something like Models.Buildings.classMethods

like image 842
Dave Avatar asked Aug 25 '16 06:08

Dave


People also ask

How do you do associations in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

How do you create a one to many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

What is polymorphic association in Sequelize?

A polymorphic association consists on two (or more) associations happening with the same foreign key. For example, consider the models Image , Video and Comment . The first two represent something that a user might post. We want to allow comments to be placed in both of them.


1 Answers

Sequelize models don’t have a method for listing associations as an array. But since models contain information about associations and associations’ options, we can parse these options to achieve the desired result.

With passing a model object to a rough function like this:

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;
}

We can get a list of associations similar to this:

[
  { 
    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'
    }
  }
]
like image 51
Vladimir Ponomarev Avatar answered Nov 16 '22 01:11

Vladimir Ponomarev