Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a composite index with associated data?

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.

like image 586
Himmators Avatar asked Jul 01 '16 12:07

Himmators


1 Answers

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'
  //   });
  // })
like image 146
Relu Mesaros Avatar answered Oct 22 '22 02:10

Relu Mesaros