【问题标题】:How to prevent inserting redundant combinations in Sequelize Node.js?如何防止在 Sequelize Node.js 中插入冗余组合?
【发布时间】:2020-08-30 15:26:52
【问题描述】:

我有一个英文单词表:WORDS,还有一个反义词表:ANTONYMS,每个单词在 WORDS 表。 ANTONYMS 表只有 2 列:ID_1ID_2,它们都引用了来自 WORDS 的 id。

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'
        }
    }
})

现在,假设我在 WORDS 表中有两个单词作为反义词,一个 id=1,另一个 id=2,行 (1, 2) ANTONYMS 中已插入 em>。如何设置约束防止用户插入冗余值(2, 1)

【问题讨论】:

    标签: sql node.js postgresql


    【解决方案1】:

    您可以在 Postgres 中创建唯一索引:

    create unique index on antonyms (least(id_1, id_2), greatest(id_1, id_2));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      相关资源
      最近更新 更多