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.

This commit is contained in:
Torsten Schulz (local)
2025-12-18 16:36:26 +01:00
parent a0206dc8cb
commit 7beed235d7

View File

@@ -476,10 +476,28 @@ const syncModelsAlways = async (models) => {
} }
try { try {
// constraints: false verhindert, dass Sequelize Foreign Keys automatisch erstellt // constraints: false wird von Sequelize ignoriert wenn Associations vorhanden sind
// Foreign Keys sollten nur über Migrations verwaltet werden // 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`); console.log(` 🔄 Syncing model ${model.name} with constraints: false`);
await model.sync({ alter: true, force: false, 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 { } finally {
// Restore VIRTUAL fields after sync // Restore VIRTUAL fields after sync
for (const [key, attr] of Object.entries(virtualFields)) { for (const [key, attr] of Object.entries(virtualFields)) {