Enhance VIRTUAL field detection in sequelize.js by implementing multiple identification methods, ensuring accurate model synchronization and preventing unintended field removals.
This commit is contained in:
@@ -422,10 +422,48 @@ const syncModelsAlways = async (models) => {
|
|||||||
const virtualFields = {};
|
const virtualFields = {};
|
||||||
|
|
||||||
// Find and temporarily remove VIRTUAL fields
|
// Find and temporarily remove VIRTUAL fields
|
||||||
|
// Check multiple ways to identify VIRTUAL fields
|
||||||
for (const [key, attr] of Object.entries(originalAttributes)) {
|
for (const [key, attr] of Object.entries(originalAttributes)) {
|
||||||
if (attr.type && attr.type.constructor && attr.type.constructor.name === 'VIRTUAL') {
|
// Check if it's a VIRTUAL field by checking the type
|
||||||
|
let isVirtual = false;
|
||||||
|
|
||||||
|
if (attr.type) {
|
||||||
|
// Method 1: Direct comparison with DataTypes.VIRTUAL
|
||||||
|
if (attr.type === DataTypes.VIRTUAL) {
|
||||||
|
isVirtual = true;
|
||||||
|
}
|
||||||
|
// Method 2: Check constructor name
|
||||||
|
else if (attr.type.constructor && attr.type.constructor.name === 'VIRTUAL') {
|
||||||
|
isVirtual = true;
|
||||||
|
}
|
||||||
|
// Method 3: Check if type key is VIRTUAL
|
||||||
|
else if (attr.type.key === 'VIRTUAL') {
|
||||||
|
isVirtual = true;
|
||||||
|
}
|
||||||
|
// Method 4: Check toString representation
|
||||||
|
else if (typeof attr.type.toString === 'function') {
|
||||||
|
const typeStr = attr.type.toString();
|
||||||
|
if (typeStr.includes('VIRTUAL') || typeStr === 'VIRTUAL') {
|
||||||
|
isVirtual = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Method 5: Check if it's an instance of VIRTUAL type
|
||||||
|
else if (attr.type instanceof DataTypes.VIRTUAL ||
|
||||||
|
(attr.type.constructor && attr.type.constructor === DataTypes.VIRTUAL.constructor)) {
|
||||||
|
isVirtual = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also check if field has a getter but no setter (common pattern for VIRTUAL fields)
|
||||||
|
if (!isVirtual && attr.get && !attr.set && !attr.field) {
|
||||||
|
// This might be a VIRTUAL field, but be careful not to remove real fields
|
||||||
|
// Only remove if we're certain it's VIRTUAL
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isVirtual) {
|
||||||
virtualFields[key] = attr;
|
virtualFields[key] = attr;
|
||||||
delete model.rawAttributes[key];
|
delete model.rawAttributes[key];
|
||||||
|
console.log(` ⚠️ Temporarily removed VIRTUAL field: ${key} from model ${model.name}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user