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

226
Vistas
I cannot delete a record "Cannot delete or update a parent row: a foreign key constraint fails FOREIGN KEY (`forumId`) REFERENCES `forums` (`id`))"

I am trying to delete my forum and I would like that when I delete the forum all the members who are in the forum are also deleted here is the code of the controllers

module.exports.deleteGroup = async (req, res, next) => {

    const token = req.cookies.jwt;
    const decoded = jwtAuth.verify(token, process.env.TOKEN_SECRET);
    const userTokenId = decoded.id;

    try {
        const { id } = req.params;

        const currentUser = await User.findByPk(userTokenId);

        if (!currentUser) return res.status(404).json('You must be logged in to make this request');

        const forum = await Forum.findOne({ where: { id } });

        if (!forum) return res.status(404).json("This forum does not exist please try again!");

        if (forum.createByUserId === currentUser.id || currentUser.isAdmin) {

            const deleteForum = await Forum.destroy({ where: { id } });

            if (deleteForum) {

                const deleteMembers = await ForumMember.destroy({ where: {} });

                return res.status(200).json(`The forum ${forum.name} has been deleted`);
            }
            else {
                return res.status(401).json(`You are not authorized to delete this forum`)
            }
        }

    } catch (error) {
        res.status(500).json(error.message)
    }

}

My associations

//Users

models.User.belongsToMany(models.Forum, {
        through: models.ForumMember,
        foreignKey: 'userId',
        otherKey: 'forumId'

      });

//Forums

models.Forum.belongsToMany(models.User, { through: models.ForumMember, foreignKey: 'forumId', otherKey: 'userId', });

//ForumMember

models.ForumMember.belongsTo(models.Forum, {
        foreignKey: 'forumId',
        as: 'groups'
      });
      models.ForumMember.belongsTo(models.User, {
        foreignKey: 'userId',
        as: 'members'
      });
    }
  };



ForumMember.init({
    forumId: {
      type: DataTypes.INTEGER,
      references: {
        model: 'Forum',
        key: 'id'
      },

    },
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: 'User',
        key: 'id'
      },

Now when I execute on PostMan I get this response: "Cannot delete or update a parent row: a foreign key constraint fails (groupomania_database_development.forummembers, CONSTRAINT forummembers_ibfk_1 FOREIGN KEY (forumId) REFERENCES forums (id))" I think I have a problem with my associations. I'm a newbie on sequelize and I would like to have your help please

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

First, you need to delete child records in junk table and the final step would be the deletion of a forum.
Second, you didn't indicate a condition in ForumMember.destroy so Sequelize tries to delete all rows in ForumMeber regardless what forum they belong to.

const deleteMembers = await ForumMember.destroy({ where: { forumId: id } });
const deleteForum = await Forum.destroy({ where: { id } });

if (deleteForum) {
  return res.status(200).json(`The forum ${forum.name} has been deleted`);
}

Third, to avoid inconsistent data in DB you need to use transactions if you make several modifications:

await sequelize.transaction(async (tr) => {
  const deleteMembers = await ForumMember.destroy({ where: { forumId: id }, transaction: tr });
  const deleteForum = await Forum.destroy({ where: { id }, transaction: tr });
  ...
});
about 4 years ago · Santiago Gelvez 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