Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
No puedo eliminar un registro "No se puede eliminar o actualizar una fila principal: una restricción de clave externa falla FOREIGN KEY (`forumId`) REFERENCES `forums` (`id`))"

estoy tratando de borrar mi foro y me gustaria que cuando borre el foro todos los miembros que estan en el foro tambien se borre aqui esta el codigo de los controladores

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

mis asociaciones

//Usuarios

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

//Foros

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

//Miembro del foro

 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' },

Ahora, cuando ejecuto en PostMan, recibo esta respuesta: "No se puede eliminar o actualizar una fila principal: falla una restricción de clave externa ( groupomania_database_development . forummembers , CONSTRAINT forummembers_ibfk_1 FOREIGN KEY ( forumId ) REFERENCES forums ( id ))" Creo que tengo un problema con mis asociaciones. Soy un novato en Sequelize y me gustaría contar con su ayuda, por favor.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Primero, debe eliminar los registros secundarios en la tabla de basura y el paso final sería la eliminación de un foro.
En segundo lugar, no indicó una condición en ForumMember.destroy , por lo que Sequelize intenta eliminar todas las filas en ForumMeber independientemente del foro al que pertenezcan.

 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`); }

En tercer lugar, para evitar datos inconsistentes en la base de datos, debe usar transacciones si realiza varias modificaciones:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!