最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sequelize - How to listview all columns of existing model - Stack Overflow

programmeradmin5浏览0评论

I know a simple answer could be query table with all attributes returned.

However, since the models are defined in code, I want to know is it possible to get the result without querying database? Or, if query is necessary, which query is the optimised one?

Btw, I am using Sequelize V5 and Mysql 5.7.

I know a simple answer could be query table with all attributes returned.

However, since the models are defined in code, I want to know is it possible to get the result without querying database? Or, if query is necessary, which query is the optimised one?

Btw, I am using Sequelize V5 and Mysql 5.7.

Share Improve this question asked Jan 8, 2020 at 5:17 leelee 1311 gold badge1 silver badge11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

You can iterate over rawAttributes of the Model class

for( let key in Model.rawAttributes ){
    console.log('Field Name: ', key); // this is name of the field
    console.log('Field Type: ', Model.rawAttributes[key].type.key); // Sequelize type of field
}

The keys of rawAttributes are the field names aka column names; the values of rawAttributes are the Sequelize definitions of those columns, including properties explained in the init/define methods., such as type, allowNull, defaultValue, unique, etc...

Remember to check rawAttributes after you create any associations and any other setup on your Model (Model.hasOne() or Model.belongsTo(), anything in your Model.associate() function), otherwise the attributes object won't include foreign key columns.

Side-note, in Sequelize v4, Model.attributes===Model.rawAttributes, so they are aliases for the same thing.

In Sequelize v6+, you can use Model.getAttributes(), which is documented

You can also use this as an answer:

for( let key of Object.keys(models.Modelname.attributes))   {
      columns.push({
          name:key,
          type:models.Modelname.attributes[key].type.key
      });
}

It seems each model has an attribute "rawAttributes" which include all columns name. This may not be the official way, but it can solve my problem.

发布评论

评论列表(0)

  1. 暂无评论