In Sequelize, you can define a unique index for multiple columns by specifying the indexes option when defining the model. This option enables you to define one or more indexes, each consisting of one or more fields. Specifically, the unique: true property indicates that this is a unique index, meaning the combined values of the indexed columns must be unique.
Below is a concrete example. Suppose we have a User model, and we want to create a unique index on the email and username fields:
javascriptconst User = sequelize.define('user', { // Define other fields email: { type: Sequelize.STRING, allowNull: false }, username: { type: Sequelize.STRING, allowNull: false } }, { // Define indexes here indexes: [{ unique: true, fields: ['email', 'username'] }] });
In this example, indexes is an array where each element defines an index. Here, we define an index object with unique: true indicating it is a unique index, and fields: ['email', 'username'] specifying that the index includes the email and username fields. This ensures that the combination of email and username for each user is unique.
This approach is highly effective in preventing duplicate data insertion, especially when working with data models that have multiple constraint conditions. For instance, in a multi-tenant system, you might need to ensure that usernames are unique within the same tenant but can repeat across different tenants. In such cases, you can include the tenant ID as part of the index to achieve this.