I've been trying to use Sequelize to manage a store front mysql db. I followed the docs here - https://sequelize.org/master/manual/assocs.html
And did (like they said)
const Customer = sequelize.define(
"customers",
{
customer_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: DataTypes.STRING,
},
{ tableName: "customers" }
);
const Order = sequelize.define(
"orders",
{
order_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
customer_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ tableName: "orders" }
);
and then announce the foregin key like so:
Customer.hasMany(Order, {
foreignKey: 'customer_id'
});
Order.belongsTo(Customer);
And it creates duplicate foregin key, both the customer_id I specified and customerID as the default one. I can overcome this by also defying foreginKey option in the belongsTo tab. But even then I get this weird behavior that every time I run the server it "adds" another, like in the picture (from heidiSQL).
I have tried to remove the field from the define() method like @tam.teixeira suggested
And replaced the code to be:
Customer.hasMany(Order, { foreignKey: "customerID"});
Order.belongsTo(Customer);
But it still creates 2 foreginKey that way
[![enter code here][2]][2]
You need to remove the definition of
customer_id: {
type: DataTypes.INTEGER,
allowNull: false,
}
from the orders model, sequelize automatically handles that field, also since its NOT NULL you need to add that condition to the association :
Customer.hasMany(Order, {
foreignKey: {
name: 'customer_id',
allowNull: false
}
});