如何在sequelize中定义多列的唯一索引

2022-01-19 00:00:00 mysql sequelize.js

如何在 sequelize.例如,我想在 user_id、count 和 name 上添加唯一索引.

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 = sequelize.define('Tag', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        user_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
        },
        count: {
            type: DataTypes.INTEGER(11),
            allowNull: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: true,
        })

推荐答案

可以参考这个文档 http://docs.sequelizejs.com/en/latest/docs/models-definition/#indexes

您将需要如下所示更改您的定义并调用同步

You will need to change your definition like shown below and call sync

var Tag = sequelize.define('Tag', {
    id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    user_id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
    },
    count: {
        type: DataTypes.INTEGER(11),
        allowNull: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: true,
    }
},
{
    indexes: [
        {
            unique: true,
            fields: ['user_id', 'count', 'name']
        }
    ]
});

相关文章