Unique constraint across foreign keys in Sequelize model

老子叫甜甜 提交于 2019-12-19 05:22:53

问题


I have a simple Sequelize model that is associated with other models.

module.exports = function (sequelize, DataTypes) {
  var Votes = sequelize.define('Votes', {
    isUpVote: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function (models) {
        Votes.belongsTo(models.Track);
        Votes.belongsTo(models.User);
      }
    }
  });

  return Votes;
}

Sequelize will generate a table with an id, TrackId, UserId and isUpVote.

I want to set a UNIQUE constraint across TrackId and UserId (i.e. a composite index ensuring that there is only one vote record for a given track and user).

How can this be done?


回答1:


you can use the unique constraint and give it a string rather than a bool. Then another other fields with the same string will become part of the same composite index.

i.e.:

module.exports = function (sequelize, DataTypes) {
   var Votes = sequelize.define('Votes', {
      isUpVote: {
          type: DataTypes.BOOLEAN,
          unique: 'myCompositeIndexName'
      },
      TrackId: {
          type: DataType.INTEGER
          unique: 'myCompositeIndexName',
      },
      UserId: {
          type: DataType.INTEGER
          unique: 'myCompositeIndexName',
      }
   }, {
       classMethods: {
           associate: function (models) {
               Votes.belongsTo(models.Track);
               Votes.belongsTo(models.User);
           }
       }
    });

    return Votes;
}

(^Not tested, just off the top of my head!)

The problem with this is that this will only occur during the creation of a table. If you table already exists, you can achieve this by using the migrations feature of sequelize-cli.

I really hope this helps else at least points you in the right direction. If you are still stuck, I recommend you go to the IRC channel for sequelize as it seems to be pretty active.



来源:https://stackoverflow.com/questions/29551941/unique-constraint-across-foreign-keys-in-sequelize-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!