Sequelize Table name inference
Introduction
In Sequelize, table name inference refers to the way Sequelize determines the name of the database table associated with a model when you don't explicitly specify it. Sequelize will infer the table name based on the model's name, but there are some conventions and options you can use to control this behavior.
Key Points about Table Name Inference -
i) Default Behavior (Pluralization)
ii) Specifying the Table Name
iii) Disable Pluralization
iv) Global ConfigurationDefault Behavior (Pluralization)
By default, Sequelize assumes that your table names are the plural form of your model names. For example, if you have a model named
User
, Sequelize will infer the table name asUsers
.Sequelize uses the
pluralize
function (from theinflection
library) to generate the plural form of the model name.const User = sequelize.define('User', { // model attributes }); // Sequelize infers table name as 'Users'
Specifying the Table Name
If you don't want Sequelize to pluralize the table name, or if you want to use a specific table name, you can explicitly set the table name using the
tableName
option.const User = sequelize.define('User', { // model attributes }, { tableName: 'User' // Explicitly set the table name });
In this example, the table name will be
User
instead of the defaultUsers
.Disable Pluralization
If you prefer not to pluralize the table names across your project, you can disable pluralization globally by setting the
freezeTableName
option totrue
in your model definition.const User = sequelize.define('User', { // model attributes }, { freezeTableName: true // Disables pluralization });
When
freezeTableName
is set totrue
, Sequelize will use the model name as the table name without any modifications.Global Configuration
You can also configure Sequelize globally to use singular table names for all models by setting
freezeTableName
in the Sequelize constructor.const sequelize = new Sequelize('database', 'username', 'password', { // other options define: { freezeTableName: true } });
This setting will apply to all models defined in this Sequelize instance, making them use the model name as the table name without pluralization.
Example
const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'postgres', // other options define: { freezeTableName: true // Use model names as table names directly } }); const User = sequelize.define('User', { // model attributes }); // The inferred table name will be 'User' (not 'Users')
Default: Sequelize pluralizes the model name to infer the table name.
Explicit Table Name: Use
tableName
to set the table name explicitly.Disable Pluralization: Use
freezeTableName
to prevent Sequelize from altering the model name for the table name, either per model or globally.