Sequelize 模型中跨外键的唯一约束 [英] Unique constraint across foreign keys in Sequelize model

查看:69
本文介绍了Sequelize 模型中跨外键的唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与其他模型相关联的简单 Sequelize 模型.

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 将生成一个带有 idTrackIdUserIdisUpVote 的表格.

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

我想在 TrackIdUserId 之间设置一个 UNIQUE 约束(即一个复合索引,确保只有一个投票记录)给定的曲目和用户).

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).

如何做到这一点?

推荐答案

您可以使用唯一约束并为其指定字符串而不是布尔值.然后另一个具有相同字符串的其他字段将成为同一复合索引的一部分.

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.

即:

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!)

这样做的问题是,这只会在创建表时发生.如果您的表已经存在,您可以使用 sequelize-cli 的迁移功能来实现这一点.

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.

我真的希望这会有所帮助,至少可以为您指明正确的方向.如果你还是卡住了,我建议你去 IRC 频道看续集,因为它似乎很活跃.

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.

这篇关于Sequelize 模型中跨外键的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆