Sql 如何防止在Sequelize Node.js中插入冗余组合?
我有一个英文单词表:单词,还有一个反义词表:反义词,每个单词在单词表中都有一个唯一的整数id。反义词表只有两列:ID_1和ID_2,都引用了单词的IDSql 如何防止在Sequelize Node.js中插入冗余组合?,sql,node.js,postgresql,Sql,Node.js,Postgresql,我有一个英文单词表:单词,还有一个反义词表:反义词,每个单词在单词表中都有一个唯一的整数id。反义词表只有两列:ID_1和ID_2,都引用了单词的ID const WORDS = database.define('WORDS', { id: { type: Sequelise.INTEGER, primaryKey: true, autoIncrement: true }, word: { type: Seq
const WORDS = database.define('WORDS', {
id: {
type: Sequelise.INTEGER,
primaryKey: true,
autoIncrement: true
},
word: {
type: Sequelise.STRING,
unique: true,
validate: {
is: ['^[a-z ]{2,30}$']
},
allowNull: false
},
definition: {
type: Sequelise.TEXT,
allowNull: true,
validate: {
is: ['^[a-z0-9 .,;]{10,500}$|^$', 'i']
}
}
})
const ANTONYMS = database.define('ANTONYMS', {
id_1: {
type: Sequelise.INTEGER,
primaryKey: true,
references: {
model: WORDS,
key: 'id'
}
},
id_2: {
type: Sequelise.INTEGER,
unique: true,
references: {
model: WORDS,
key: 'id'
}
}
})
现在,假设我在单词表中有两个单词作为反义词,一个id=1,另一个id=2,并且行(1,2)已经插入到反义词中。如何设置约束以防止用户插入冗余值(2,1)?您可以在Postgres中创建唯一索引:
create unique index on antonyms (least(id_1, id_2), greatest(id_1, id_2));