Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define unique index on multiple columns in sequelize

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,         }) 
like image 428
lboyel Avatar asked Feb 13 '17 01:02

lboyel


People also ask

What is unique index with multiple columns?

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.

How do you define index in Sequelize?

createTable('Item', { // columns... }). then(() => queryInterface. addIndex('Item', ['OwnerId'])) . then(() => { // perform further operations if needed });


1 Answers

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']         }     ] }); 
like image 50
Keval Gohil Avatar answered Sep 20 '22 14:09

Keval Gohil