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