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:
@@ -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)) {
|
||||
|
||||
Reference in New Issue
Block a user