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

192
Visualizações
Sequelize - foreign key constraints

I have a problem while undoing my migrations using sequelize-cli.

I get this error :

== 20211023095522-create-product: reverting =======

ERROR: Cannot delete or update a parent row: a foreign key constraint fails

Here is my model:

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Product extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      this.hasOne(models.ProductInfo, {
        foreignKey: "product_id",
      });

      this.belongsToMany(models.Size, {
        through: "product_size",
        foreignKey: "product_id",
      });

      this.belongsToMany(models.Category, {
        through: "product_category",
        foreignKey: "product_id",
      });

      this.belongsToMany(models.Color, {
        through: "product_color",
        foreignKey: "product_id",
      });
    }

    toJSON() {
      return {
        ...this.get(),
        updatedAt: undefined,
      };
    }
  }
  Product.init(
    {
      stock: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
    },
    {
      sequelize,
      modelName: "Product",
    }
  );
  return Product;
};

And here is an associated model of product (they are all associated the same way):

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Size extends Model {

    static associate(models) {
      // define association here
      this.belongsToMany(models.Product, {
        through: "product_size",
        foreignKey: "size_id",
      });
    }
  }
  Size.init(
    {
      name: { type: DataTypes.STRING, allowNull: false },
    },
    {
      sequelize,
      modelName: "Size",
    }
  );
  return Size;
};

I tried adding onDelete: "Cascade" and onUpdate: "CASCADE" in each of my associations parameters but it didn't solved my problem.

Do you have any idea?

about 4 years ago · Juan Pablo Isaza
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