From 7beed235d79158d54cb9a024fd9976f6f24c6b9d Mon Sep 17 00:00:00 2001 From: "Torsten Schulz (local)" Date: Thu, 18 Dec 2025 16:36:26 +0100 Subject: [PATCH] Improve model synchronization in sequelize.js by temporarily removing associations to prevent automatic foreign key creation. Add logging for association management during the sync process, ensuring clarity in model handling. --- backend/utils/sequelize.js | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/backend/utils/sequelize.js b/backend/utils/sequelize.js index b3069bb..3d9c387 100644 --- a/backend/utils/sequelize.js +++ b/backend/utils/sequelize.js @@ -476,10 +476,28 @@ const syncModelsAlways = async (models) => { } try { - // constraints: false verhindert, dass Sequelize Foreign Keys automatisch erstellt - // Foreign Keys sollten nur über Migrations verwaltet werden + // constraints: false wird von Sequelize ignoriert wenn Associations vorhanden sind + // Wir müssen die Associations temporär entfernen, um Foreign Keys zu verhindern + const originalAssociations = model.associations ? { ...model.associations } : {}; + const associationKeys = Object.keys(originalAssociations); + + // Entferne temporär alle Associations, damit Sequelize keine Foreign Keys erstellt + if (associationKeys.length > 0) { + console.log(` ⚠️ Temporarily removing ${associationKeys.length} associations from ${model.name} to prevent FK creation`); + // Lösche alle Associations temporär + for (const key of associationKeys) { + delete model.associations[key]; + } + } + console.log(` 🔄 Syncing model ${model.name} with constraints: false`); await model.sync({ alter: true, force: false, constraints: false }); + + // Stelle die Associations wieder her + if (associationKeys.length > 0) { + console.log(` ✅ Restoring ${associationKeys.length} associations for ${model.name}`); + model.associations = originalAssociations; + } } finally { // Restore VIRTUAL fields after sync for (const [key, attr] of Object.entries(virtualFields)) {