Sequelize timestamp names

自作多情 提交于 2020-08-06 07:41:21

问题


I have a small issue with sequelize that I can't get around and it irritates the hell out of me.

I'm using camelCase for all my model attributes but I'm using snake case to persist them into the database (postgres). That part works fine except if I want to use sequelize timestamps option.

If I set underscored: false, timestamps get persisted to the database in camelCase.

If I set underscored: true, they get persisted in snake_case but then they are in snake_case on the model.

What I want to achieve is snake_case in the database and camelCase on the model for model timestamps.

It feels like those 2 options are mutually exclusive.

Thank you


回答1:


Yes, you can. Key is to combine model setting and field mappings. That's what I do: When you defining your model, add following field mappings:

createdAt: { type: Sequelize.DATE, field: 'created_at' },
updatedAt: { type: Sequelize.DATE, field: 'updated_at' },
deletedAt: { type: Sequelize.DATE, field: 'deleted_at' }

Then in model options:

timestamps: true,
underscored: true

Works like a charm for me. In this way you can also use paranoid option correctly.




回答2:


You can do some workaround like this:

UPDATE: As Sergey stated in his answer, we need to keep timestamp option to be true, so I fixed that.

new Sequelize(foo, bar, baz, {
  define: {
    timestamps: true,
    underscored: true
    createdAt: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        name: 'createdAt',
        field: 'created_at'
    }
    updatedAt: {
        type: DataTypes.DATE,
        name: 'updatedAt',
        field: 'updated_at'
    }
  }
});

Related issue



来源:https://stackoverflow.com/questions/48209543/sequelize-timestamp-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!