用关联的数据创build一个复合索引?

我有一个用户表和一个userAttributes表。 每个用户只能有一个每个userAttribute的实例,所以我想创build一个列名和userId(这是由userAttributes.belongsTo创build的)复合唯一索引。这怎么能做到?

UserAttribute = sequelize.define('userAttributes', { name: { type: Sequelize.STRING, allowNull: false, unique: 'nameIndex', validate: { isIn: [['phone', 'name','driverRequest']], } }, value: { type: Sequelize.STRING, allowNull: false }, }); User.hasMany(userAttributes, {unique: 'nameIndex'}); userAttributes.belongsTo(User, {unique: 'nameIndex'}); 

我试着添加唯一的nameIndex没有成功,它似乎只适用于名称列。

Solutions Collecting From Web of "用关联的数据创build一个复合索引?"

 var Sequelize = require('sequelize'); var sequelize = new Sequelize('<yourDatabaseName>', '<yourUserName>', '<yourPassword', { host: '<ip>' }); var User = sequelize.define('user', { id: { type: Sequelize.STRING, allowNull: false, primaryKey: true }, }); var UserAttribute = sequelize.define('userattribute', { userId: { type: Sequelize.STRING, allowNull: false, unique: 'compositeIndex', references: { model: User, key: "id" } }, name: { type: Sequelize.STRING, allowNull: false, unique: 'compositeIndex' } }); User.hasOne(UserAttribute, { as: "UserAttribute" }) UserAttribute.belongsTo(User, { foreignKey: "userId", as: 'UserId' }) sequelize.sync({ // use force to delete tables before generating them force: true }).then(function() { console.log('tables have been created'); return User.create({ id: 'randomId1' }); }) .then(function() { console.log('tables have been created'); return User.create({ id: 'randomId2' }); }) .then(function() { return UserAttribute.create({ userId: 'randomId1', name: 'name1' }); }) .then(function() { return UserAttribute.create({ userId: 'randomId2', name: 'name1' }); }) // // generates Validation Error // .then(function() { // return UserAttribute.create({ // userId: 'randomId1', // name: 'name1' // }); // })