How to add primary key constraint in Sequelize

Sequelize provides the primaryKey option that you can add to your Sequelize model attributes. The primaryKey option allows you to assign the PRIMARY KEY constraint to your model columns.

const User = sequelize.define("User", {
  user_id : {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  firstName: {
    type: Sequelize.STRING,
  },
  isActive: {
    type: Sequelize.BOOLEAN,
    defaultValue: false,
  },
},
{
  timestamps: false,
});

When you sync() the above Sequelize model, the user_id column will be created as the PRIMARY KEY column of the Users table in your database.

You can also add multiple primary keys to your SQL table by specifying the primaryKey option to multiple attributes.

The following Sequelize model:

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
    primaryKey: true,
  },
  lastName: {
    type: Sequelize.STRING,
    primaryKey: true,
  },
},
{
  timestamps: false,
});

Leave a comment

Your email address will not be published. Required fields are marked *