Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize timestamp names

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

like image 356
J.D. Avatar asked Jan 11 '18 14:01

J.D.


People also ask

How do I use timestamp in Sequelize?

If you want to use the TIMESTAMP type, then you need to manually specify the attributes as TIMESTAMP types in your model as shown below: const User = sequelize. define( "User", { firstName: Sequelize. STRING, createdAt: { type: "TIMESTAMP", defaultValue: sequelize.

How do you make a Sequelize use singular table names?

const People = sequelize. define('people', { name: DataTypes. STRING, }, { hooks: { beforeCount (options) { options. raw = true; } }, tableName: 'people', name: { singular: 'person', plural: 'people' } });

What is Sequelize model name?

A model is an abstraction that represents a table in your database. In Sequelize, it is a class that extends Model. The model tells Sequelize several things about the entity it represents, such as the name of the table in the database and which columns it has (and their data types). A model in Sequelize has a name.


1 Answers

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.

like image 158
Sergey Yarotskiy Avatar answered Sep 28 '22 05:09

Sergey Yarotskiy