Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

317
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda