2017-02-13 17 views
5

Làm cách nào để xác định chỉ mục duy nhất trên kết hợp các cột trong phần tiếp theo. Ví dụ tôi muốn thêm một chỉ mục duy nhất trên user_id, count và name.Cách xác định chỉ mục duy nhất trên nhiều cột trong phần tiếp theo

var Tag = sequelize.define('Tag', { 
     id: { 
      type: DataTypes.INTEGER(11), 
      allowNull: false, 
      primaryKey: true, 
      autoIncrement: true 
     }, 
     user_id: { 
      type: DataTypes.INTEGER(11), 
      allowNull: false, 
     }, 
     count: { 
      type: DataTypes.INTEGER(11), 
      allowNull: true 
     }, 
     name: { 
      type: DataTypes.STRING, 
      allowNull: true, 
     }) 

Trả lời

11

Bạn có thể tham khảo doc này http://docs.sequelizejs.com/en/latest/docs/models-definition/#indexes

Bạn sẽ cần phải thay đổi, định nghĩa của bạn như hình dưới đây và gọi sync

var Tag = sequelize.define('Tag', { 
    id: { 
     type: DataTypes.INTEGER(11), 
     allowNull: false, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    user_id: { 
     type: DataTypes.INTEGER(11), 
     allowNull: false, 
    }, 
    count: { 
     type: DataTypes.INTEGER(11), 
     allowNull: true 
    }, 
    name: { 
     type: DataTypes.STRING, 
     allowNull: true, 
    } 
}, 
{ 
    indexes: [ 
     { 
      unique: true, 
      fields: ['user_id', 'count', 'name'] 
     } 
    ] 
}) 
+0

đã nhận, cảm ơn! – lboyel

1

Nếu chấp nhận một không hoạt động sau đó thử vào mã bên dưới . Nó làm việc cho tôi trong trường hợp của tôi chứ không phải là chấp nhận.

var Tag = sequelize.define('Tag', { 
     id: { 
      type: DataTypes.INTEGER(11), 
      allowNull: false, 
      primaryKey: true, 
      autoIncrement: true 
     }, 
     user_id: { 
      type: DataTypes.INTEGER(11), 
      allowNull: false, 
      unique: 'uniqueTag', 
     }, 
     count: { 
      type: DataTypes.INTEGER(11), 
      allowNull: true, 
      unique: 'uniqueTag', 
     }, 
     name: { 
      type: DataTypes.STRING, 
      allowNull: true, 
      unique: 'uniqueTag', 
     }) 
1

Tôi có cùng một vấn đề để áp dụng hạn chế duy nhất tổng hợp cho nhiều cột nhưng công việc gì với Mysql, Sequelize (4.10.2) và NodeJs 8.9.4 Cuối cùng tôi cố định thông qua sau mã.

queryInterface.createTable('actions', { 
    id: { 
     type: Sequelize.INTEGER, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    system_id: { 
     type: Sequelize.STRING, 
     unique: 'actions_unique', 
    }, 
    rule_id: { 
     type: Sequelize.STRING, 
     unique: 'actions_unique', 
    }, 
    plan_id: { 
     type: Sequelize.INTEGER, 
     unique: 'actions_unique', 
    } 
}, { 
    uniqueKeys: { 
     actions_unique: { 
      fields: ['system_id', 'rule_id', 'plan_id'] 
     } 
    } 
}); 
Các vấn đề liên quan