【问题标题】:how to block insert duplicate record in node mysql for many-to-many relation?如何阻止在节点mysql中插入重复记录以实现多对多关系?
【发布时间】:2020-07-15 08:29:57
【问题描述】:

如何阻止在节点 MySQL 中为多对多关系插入重复记录?我有两个外键:id_product 和 id_customer,我想用主键 id_relation 在它们之间创建关系。此刻,我可以多次保存相同的产品和客户组合,每次创建新的 id_relation。有没有办法在将它保存到 MySQL 数据库之前先检查这种组合是否已经存在,或者有其他方法来防止重复相同的记录?

exports.create = (req, res) => {
const relation = {
    id_product: req.body.id_product,
    id_customer: req.body.id_customer
};

Relation.create(relation)
    .then(data => {
        res.send(data);
    })
    .catch(err => {
        res.status(500).send({
            message:
                err.message || "Error"
        });
    });

}

module.exports = function(sequelize, DataTypes) {
return sequelize.define('relation', {
  id: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    unique: true
  },
  id_product: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    references: {
      model: 'product',
      key: 'id' 
    },
    onDelete: 'CASCADE'
  },
  id_customer: {
    type: DataTypes.INTEGER(11),
    allowNull: false,
    references: {
      model: 'customer',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
}, {
  timestamps: false,
  tableName: 'relation'
});

};

【问题讨论】:

标签: mysql node.js database many-to-many


【解决方案1】:

首先您需要将唯一索引添加到您的表中,并在插入记录时参考此

How to ignore SequelizeUniqueConstraintError in Sequelize?

Sequelize upsert 方法文档 https://sequelize.org/master/class/lib/model.js~Model.html#static-method-upsert

ALTER TABLE table_name ADD UNIQUE INDEX(FirstName, lastName);

然后使用插入忽略来避免重复记录:

INSERT IGNORE INTO table_name (product_id, customer_id) VALUES (1, 2), (1, 2);

参考:

https://www.mysqltutorial.org/mysql-insert-ignore/

【讨论】:

    【解决方案2】:

    您可以创建 MySQL 过程以确保仅插入唯一的 id_customer 和 id_product 对。代码将如下所示:

    CREATE PROCEDURE `procedure_name`(IN relation INT,IN customer INT,IN product INT)
    BEGIN
        IF 
            (SELECT ((SELECT customer "id_custoemr", product "id_product") NOT IN (SELECT id_customer, id_product FROM table_name)))
        THEN
            INSERT INTO `table_name` (id_relation, id_customer, id_product) VALUES (relation, customer, product);
        END IF;
    END
    

    在您的 Node 应用程序中而不是运行查询,您只需要使用正确的参数调用您的过程,如下所示:

    call procedure_name(4,4,3);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2014-09-16
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多