Ich versuche, eine Hierarchie in meiner Datenbank zu laden. Ich habe eine Spalte mit parentId in meiner Tabelle, so dass jede Zeile ein Elternteil haben kann. Aber ich habe Probleme mit Rekursion und Versprechungen.Herarchie Abfrage mit Sequelize/Nodejs
function read (options) {
return serviceItemAttributeModel.findOne({
id: options.id,
id_organization: options.idOrganization
})
.then((attribute) => {
if (attribute) {
return loadChildren(attribute, attribute);
} else {
return attribute;
}
});
}
function loadChildren (root, attribute) {
return serviceItemAttributeModel.findAll({
where: {
id_parent: attribute.id
}
})
.then((attributes) => {
if (!attributes) {
return root;
} else {
attribute.serviceItemAttributes = [];
attributes.forEach(function (each) {
attribute.serviceItemAttributes.push(each);
return loadChildren(root, each);
});
}
});
}
So nenne ich lesen, ruft loadChildren rekursiv versuchen, alle Objekte zu laden (von Kindern eines Unternehmens suchen) und ich bekomme einen nicht definierten Wert. Irgendwelche Ideen?
Ich bekomme auch einen Fehler auf der Konsole: Ein Versprechen wurde in einem Handler erstellt, wurde aber nicht von ihm zurückgegeben.
EDIT:
kam nach Nosyara Hilfe, wenn diese Lösung auf. Dank !:
function read (options) {
return serviceItemAttributeModel.findOne({
where: {
id: options.attributeId,
id_organization: options.idOrganization
}
})
.then((attribute) => {
if (!attribute) {
return new Promise(function (resolve, reject) {
resolve(attribute);
});
} else {
return new Promise(function (resolve, reject) {
attribute.queryCount = 1;
resolve(attribute);
})
.then((attribute) => loadChildren(attribute, attribute));
}
});
}
function loadChildren (root, attribute) {
return new Promise(function (resolve, reject) {
return serviceItemAttributeModel.findAll({
where: {
id_parent: attribute.id
}
})
.then((attributes) => {
attributes.length = attributes.length || 0;
root.queryCount = root.queryCount - 1 + attributes.length;
if (root.queryCount === 0) {
resolve(root);
} else if (root.queryCount > 10) {
let error = new Error('Service attribute hierarchy cant have more then 10 levels');
error.statusCode = 500;
reject(error);
} else {
attribute.serviceItemAttributes = [];
attributes.forEach(function (each) {
attribute.serviceItemAttributes.push(each);
return loadChildren(root, each).then(() => {
resolve(root);
});
});
}
});
});
}
ich den Code geändert wie das Ihre sehen .... aber es immer noch nicht funktioniert hat – fredcrs
einige Fortschritte bekam ..... kann immer noch nicht Last 3. Ebene – fredcrs
der Code so weit: http://pastebin.com/Na5NHkMm – fredcrs