Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get attributes // associations by previously defined Sequelize Model?

Tags:

I need to get some data by previously defined Sequelize Model.

What I need:

* attributes list   * attribute name   * attribute type (INTEGER, STRING,...)   * was it generated by association method? * list of associations   * association type (belongsTo, hasMany, ...) 

For some reason it's rather hard to inspect Sequelize models in console:

> db.sequelize.models.Payment Payment // <- it's valid Sequelize Model {Object}, however its not inspectable  > db.sequelize.models.Payment.attributes ... type:  { type: { values: [Object] },    values: [ 'cash', 'account', 'transfer' ],    Model: Payment,    fieldName: 'type',    _modelAttribute: true,    field: 'type' }, sum:   { type:      { options: [Object],       _length: undefined,       _zerofill: undefined,       _decimals: undefined,       _precision: undefined,       _scale: undefined,       _unsigned: undefined },    Model: Payment,    fieldName: 'sum',    _modelAttribute: true,    field: 'sum' },  ... 

As you see, there is no actual info about fields types. The same happens with associations.

So, is there any reliable "official" way to extract this data from Model class without digging and reversing object?

like image 759
f1nn Avatar asked Nov 22 '15 18:11

f1nn


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.

Are there many relations in Sequelize?

The A.hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ). These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).

How do you use belongsTo in Sequelize?

You can make the Task model belongs to the User model by calling the belongsTo() method from the Task model like this: Task. belongsTo(User); The belongsTo() method above will associate the Task model with the User model, adding the UserId attribute to the Task model as the foreign key constraint.


1 Answers

Try Payment.rawAttributes, which is an object with property name as key, and an object with property details. property.type.key is a string with the type.

Payment.associations is an object of associations - the key is the name, and each association will have an associationType property - you can also do association instanceof sequelize.Association.BelongsTo etc.

like image 189
Jan Aagaard Meier Avatar answered Sep 24 '22 01:09

Jan Aagaard Meier