【问题标题】:How to use Sequelize to get list of fields and their types of a model如何使用 Sequelize 获取模型的字段列表及其类型
【发布时间】:2021-04-06 14:22:54
【问题描述】:

例如,如果我有一个包含定义字段的用户模型:{name, location, dob, value}。无论如何我可以从模型中获取此类数据的列表吗?也许甚至像

[ {var: "name" , type: "string" }, 
{var: "location" , type: "string" }, 
{var: "dob" , type: "date" }, 
{var: "value" , type: "int" }, 

【问题讨论】:

    标签: sql node.js postgresql model sequelize.js


    【解决方案1】:

    您也可以从Model.describe()获取数据类型

    const User = sequelize.model(`User`)
    const description = await User.describe()
        .then(data => {
            const res = []
            for (const [key, value] of Object.entries(data)) {
                res.push({
                    key,
                    type: value.type
                })
            }
            return res
        })
    console.log(description)
    

    输出类似于:

    [
      { key: 'id', type: 'INTEGER' },
      { key: 'name', type: 'CHARACTER VARYING(255)' },
      { key: 'location', type: 'CHARACTER VARYING(255)' },
      { key: 'value', type: 'CHARACTER VARYING(255)' },
      { key: 'createdAt', type: 'TIMESTAMP WITH TIME ZONE' },
      { key: 'updatedAt', type: 'TIMESTAMP WITH TIME ZONE' }
    ]
    

    【讨论】:

      【解决方案2】:

      您可以使用模型中的属性 rawAttributes。在你的情况下, User.rawAttributes 会给你想要的属性。

      https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        相关资源
        最近更新 更多