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
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.
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.
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.
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'
}
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With