diff --git a/core/package.json b/core/package.json index fb72037..e767b02 100644 --- a/core/package.json +++ b/core/package.json @@ -1,6 +1,6 @@ { "name": "@cool-midway/core", - "version": "7.1.3", + "version": "7.1.4", "description": "", "main": "dist/index.js", "typings": "index.d.ts", diff --git a/core/src/module/import.ts b/core/src/module/import.ts index 1feb5bb..ab5409e 100644 --- a/core/src/module/import.ts +++ b/core/src/module/import.ts @@ -103,24 +103,8 @@ export class CoolModuleImport { // 导入数据 for (const key in data) { try { - const repository = this.defaultDataSource.getRepository( - metadatas[key] - ); - if (this.ormConfig.default.type == "postgres") { - for (const item of data[key]) { - const result: any = await repository.save( - repository.create(item) - ); - if (item.id) { - await repository.update(result.id, { id: item.id }); - // 更新pgsql序列 - await this.defaultDataSource.query( - `SELECT setval('${key}_id_seq', (SELECT MAX(id) FROM ${key}));` - ); - } - } - } else { - await repository.insert(data[key]); + for (const item of data[key]) { + await this.importData(metadatas, item, key); } } catch (e) { this.coreLogger.error( @@ -140,4 +124,55 @@ export class CoolModuleImport { ); } } + + /** + * 导入数据 + * @param metadatas + * @param datas + * @param tableName + */ + async importData( + metadatas: any[], + item: any, + tableName: string, + parentItem: any = null + ) { + const repository = this.defaultDataSource.getRepository( + metadatas[tableName] + ); + // 处理当前项中的引用 + if (parentItem) { + for (const key in item) { + if (typeof item[key] === "string" && item[key].startsWith("@")) { + const parentKey = item[key].substring(1); // 移除"@"符号 + if (parentItem.hasOwnProperty(parentKey)) { + item[key] = parentItem[parentKey]; + } + } + } + } + // 插入当前项到数据库 + let insertedItem; + if (this.ormConfig.default.type == "postgres") { + insertedItem = await repository.save(repository.create(item)); + if (item.id) { + await repository.update(insertedItem.id, { id: item.id }); + await this.defaultDataSource.query( + `SELECT setval('${tableName}_id_seq', (SELECT MAX(id) FROM ${tableName}));` + ); + } + } else { + insertedItem = await repository.insert(item); + } + // 递归处理@childDatas + if (!_.isEmpty(item["@childDatas"])) { + const childDatas = item["@childDatas"]; + delete item["@childDatas"]; + for (const childKey in childDatas) { + for (const childItem of childDatas[childKey]) { + await this.importData(metadatas, childItem, childKey, item); + } + } + } + } } diff --git a/core/src/package.json b/core/src/package.json index 62db3f2..5f4268b 100644 --- a/core/src/package.json +++ b/core/src/package.json @@ -1,6 +1,6 @@ { "name": "@cool-midway/core", - "version": "7.1.3", + "version": "7.1.4", "description": "", "main": "index.js", "typings": "index.d.ts",