有没有办法通过先前定义的Sequelize Model来获取属性//关联?

f1n*_*1nn 14 model sequelize.js

我需要通过之前定义的Sequelize Model获取一些数据.

我需要的:

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

出于某种原因,在控制台中检查Sequelize模型相当困难:

> 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' },
 ...
Run Code Online (Sandbox Code Playgroud)

如您所见,没有关于字段类型的实际信息.关联也是如此.

那么,有没有可靠的"官方"方法从Model类中提取这些数据而不需要挖掘和反转对象?

Jan*_*ier 36

Try Payment.rawAttributes,具有属性名称作为键的对象,以及具有属性详细信息的对象.property.type.key是一个类型的字符串.

Payment.associations是关联的对象 - 关键是名称,每个关联都有一个associationType属性 - 你也可以做association instanceof sequelize.Association.BelongsTo等等.

  • 要获取类型作为在数据库上使用的字符串,可以执行`ModelName.rawAttributes.propertyName.type.toSql()`。 (2认同)

Dal*_*yan 6

续集 v6

rawAttributes()方法现已弃用,请改用getAttributes()方法。文档

用法示例:

import models from "./src/models/index.js"
import User from "./src/models/User.js"

console.log(models.sequelize.model('user').getAttributes())
console.log(User.getAttributes())
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想要对象键,您可以执行以下操作:`Object.keys(User.getAttributes())` (2认同)