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?
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.
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).
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.
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.
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