Sequelize compound unique constraint

Model Definition:

export default function(sequelize, DataTypes) {
   return sequelize.define('Item', {
       minor: DataTypes.INTEGER,
       major: DataTypes.INTEGER,
   });
}

Is it possible to define a pair of minor and main as a composite UNIQUE constraint?

+10
source share
4 answers

Recently, in V4, Sequelize added this to the request interface:

http://docs.sequelizejs.com/manual/tutorial/migrations.html#addconstraint-tablename-attributes-options-

queryInterface.addConstraint('Items', ['minor', 'major'], {
  type: 'unique',
  name: 'custom_unique_constraint_name'
});
+18
source

Here is a simple answer:

major: { type: DataTypes.INTEGER, unique: 'compositeIndex'},
minor: { type: DataTypes.INTEGER, unique: 'compositeIndex'}

source: http://docs.sequelizejs.com/en/latest/docs/models-definition/

You can also create a unique constraint using your ownToMany associations, if this is a join table:

Major = sequelize.define('major', {})
Minor = sequelize.define('minor', {})

Major.belongsToMany(Project)
Minor.belongsToMany(User)

Source: http://docs.sequelizejs.com/en/v3/docs/associations/

. , SQL- up:

  up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Item', {
  major: {
    allowNull: false,
    type: Sequelize.INTEGER
  },
  minor: {
    allowNull: false,
    type: Sequelize.INTEGER
  },
})
.then(function() {
  return queryInterface.sequelize.query(
    'ALTER TABLE 'Item' ADD UNIQUE 'unique_index'('major', 'minor')'
  );
});

:

Sequelize,

Sequelize

+10
   queryInterface.createTable('Item', {
        minor: {
            type: Sequelize.INTEGER,
        },
        major: {
            type: Sequelize.INTEGER,
        }
    }, {
        uniqueKeys: {
            Items_unique: {
                fields: ['minor', 'major']
            }
        }
    });
+1
source

You can use something like this:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.transaction(t => {
      return queryInterface.createTable('item',
        {
          minor: {
            type: Sequelize.INTEGER,
          },
          major: {
            type: Sequelize.INTEGER,
          }
        }, { transaction: t }
      ).then(() => {
        return queryInterface.addConstraint(
          'item',
          ['minor', 'major'],
          {
            type: 'unique',
            name: 'Items_unique'
          },
          {
            transaction: t
          }
        );
      });
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('item');
  }
}
0
source

Source: https://habr.com/ru/post/1623338/


All Articles