Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

319
Vistas
Sequelize hasOne() / hasMany() and BelongsTo() duplicate the foregin key (creates new one and re-define it), and re-announce it as key

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).

See 17 foregin key for the same column

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]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
  }
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda