mysql多对多出现重复,如何在多对多关系中阻止在节点mysql中插入重复记录?

How to block insert duplicate record in node MySQL for many-to-many relation ? I have two foreign keys: id_product and id_customer and I would like to create relation between them with primary key id_relation. For this moment I can save multiple times the same combination of product and customer what each time creates new id_relation. Is there a way to check first of such combination already exists before saving it into MySQL database or another way to prevent duplication of the same record?

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'

});

};

解决方案

First you need to add the UNIQUE index to your table and when inserting record refer this

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

then using insert ignore to avoid duplicate records:

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

reference:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值