Skip to content

Instantly share code, notes, and snippets.

@iteufel
Last active July 24, 2019 10:43
Show Gist options
  • Save iteufel/fc84059d43fabbfe13bb65a132d17fc0 to your computer and use it in GitHub Desktop.
Save iteufel/fc84059d43fabbfe13bb65a132d17fc0 to your computer and use it in GitHub Desktop.
TypeOrm delete Nested
import { getManager } from 'typeorm';
import * as dotProp from 'dot-prop';
export async function deleteNested (item: any) {
const meta = getRemoveRelations(item.constructor, '');
const res = await getManager().findOneOrFail(item.constructor, item, {
relations: meta
})
await getManager().remove(res);
for (const path of meta) {
const prop = dotProp.get(res, path);
await getManager().remove(prop);
}
}
function getRemoveRelations (entity: any, path: string) {
let delData = [];
const meta = getManager().connection.getMetadata(entity)
for (const relation of meta.ownRelations) {
if (relation.isOneToOne) {
const cpath = [...(path.length > 0 ? [path] : []), relation.propertyPath].join('.');
delData = [...delData, cpath, ...getRemoveRelations(relation.type, cpath)]
}
}
return delData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment