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, })
A unique index ensures the index key columns do not contain any duplicate values. A unique index may consist of one or many columns. If a unique index has one column, the values in this column will be unique. In case the unique index has multiple columns, the combination of values in these columns is unique.
createTable('Item', { // columns... }). then(() => queryInterface. addIndex('Item', ['OwnerId'])) . then(() => { // perform further operations if needed });
You can refer to this doc 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'] } ] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With