I have a User-table and a userAttributes table. Every user can only have one instance of each userAttribute, so I would like to create a composite unique index for the columns name and userId(That is created by userAttributes.belongsTo.) How can this be done?
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'});
I tride adding the unique nameIndex with no success, it seems to only apply to the name-column.
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'
// });
// })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With