如何在使用Postgresql时在SequelizeJS模型中添加不区分大小写的惟一约束?

时间:2022-12-09 19:24:26
var Model = sequelize.define('Company', {
  name: {
    type: DataTypes.STRING,
    unique: true
  }
}

In the above example, unique: true is case sensitive. It allows both "sample" and "Sample" to be saved in the db. Is there a built-in way to do this in sequelize without having to write a custom validator?

在上面的示例中,unique: true是区分大小写的。它允许在db中保存“sample”和“sample”。是否有一种内置的方法可以在不需要编写自定义验证器的情况下在sequelize中实现这一点?

1 个解决方案

#1


4  

I'd suggest adding a functional unique index as seen here: http://www.postgresql.org/message-id/c57a8ecec259afdc4f4caafc5d0e92eb@mitre.org

我建议添加一个功能独特的索引:http://www.postgresql.org/message- id/c57a8ec259afdc4f4f4fafc5d0e92eb@mitre.org

var Model = sequelize.define('Company', {
  name: {
    type: DataTypes.STRING
  }
}, {
  indexes: [
    { name: 'unique_name', unique: true, fields: [sequelize.fn('lower', sequelize.col('name')) }
  ]
});

#1


4  

I'd suggest adding a functional unique index as seen here: http://www.postgresql.org/message-id/c57a8ecec259afdc4f4caafc5d0e92eb@mitre.org

我建议添加一个功能独特的索引:http://www.postgresql.org/message- id/c57a8ec259afdc4f4f4fafc5d0e92eb@mitre.org

var Model = sequelize.define('Company', {
  name: {
    type: DataTypes.STRING
  }
}, {
  indexes: [
    { name: 'unique_name', unique: true, fields: [sequelize.fn('lower', sequelize.col('name')) }
  ]
});