How to define unique index on multiple columns in sequelize

前端 未结 6 2143
半阙折子戏
半阙折子戏 2020-12-13 06:50

How do I define a unique index on a combination of columns in sequelize. For example I want to add a unique index on user_id, count and name.

var Tag = sequ         


        
6条回答
  •  难免孤独
    2020-12-13 07:09

    I prefer sequelize sync method with composite unique, If not passing indexes name u will get a error as below on adding many indexes in index array.

    error: SequelizeDatabaseError: Identifier name 'LONG_NAME' is too long

    module.exports = function (sequelize: any, DataTypes: any) {
    return sequelize.define('muln_user_goals_transaction', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
        },
        name: {
            type: DataTypes.STRING(),
            allowNull: false,
        },
        email: {
            type: DataTypes.STRING(),
            allowNull: false,
        },
        phone: {
            type: DataTypes.STRING(),
            allowNull: false,
        },
        amount: {
            type: DataTypes.INTEGER(8),
            allowNull: false
        },
        deleted: {
            type: DataTypes.BOOLEAN,
            defaultValue: false,
        },
    }, {
        tableName: 'muln_user_goals_transaction',
        timestamps: false,
        indexes: [
            {
                name: 'unique_index',
                unique: true,
                fields: ['name', 'email', 'phone', 'amount', 'deleted']
            }
        ],
        defaultScope: {
            where: {
                deleted: false
            }
        }
    });
    };
    

提交回复
热议问题