78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
import { Bootstrap } from '@midwayjs/bootstrap';
|
|
import { Product } from '../../entity/product.entity';
|
|
import { SiteSku } from '../../entity/site-sku.entity';
|
|
import { InjectEntityModel } from '@midwayjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Provide } from '@midwayjs/core';
|
|
|
|
@Provide()
|
|
export class MigrateSiteSkus {
|
|
@InjectEntityModel(Product)
|
|
productModel: Repository<Product>;
|
|
|
|
@InjectEntityModel(SiteSku)
|
|
siteSkuModel: Repository<SiteSku>;
|
|
|
|
async main() {
|
|
console.log('开始迁移 siteSkus 数据...');
|
|
|
|
try {
|
|
// 获取所有产品
|
|
const products = await this.productModel.find();
|
|
|
|
console.log(`找到 ${products.length} 个产品需要检查 siteSkus 数据`);
|
|
|
|
let migratedCount = 0;
|
|
|
|
for (const product of products) {
|
|
// 检查 siteSkus 是否为字符串数组
|
|
if (Array.isArray(product.siteSkus) && product.siteSkus.length > 0) {
|
|
for (const siteSku of product.siteSkus) {
|
|
// 检查是否已存在该 SKU
|
|
const existingSiteSku = await this.siteSkuModel.findOne({
|
|
where: { sku: siteSku.sku },
|
|
});
|
|
|
|
if (!existingSiteSku) {
|
|
// 创建新的 SiteSku 实体
|
|
const siteSku = new SiteSku();
|
|
siteSku.sku = siteSku.sku;
|
|
siteSku.productId = product.id;
|
|
siteSku.isOld = true;
|
|
|
|
await this.siteSkuModel.save(siteSku);
|
|
migratedCount++;
|
|
} else if (!existingSiteSku.productId) {
|
|
// 如果已存在但未关联产品,则关联
|
|
existingSiteSku.productId = product.id;
|
|
existingSiteSku.isOld = true;
|
|
await this.siteSkuModel.save(existingSiteSku);
|
|
migratedCount++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(`成功迁移 ${migratedCount} 条 siteSku 数据`);
|
|
console.log('数据迁移完成!');
|
|
} catch (error) {
|
|
console.error('数据迁移失败:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 运行迁移
|
|
if (require.main === module) {
|
|
Bootstrap
|
|
.run()
|
|
.then(async (app) => {
|
|
const migrateService = app.get(MigrateSiteSkus);
|
|
await migrateService.main();
|
|
})
|
|
.catch(error => {
|
|
console.error('启动失败:', error);
|
|
process.exit(1);
|
|
});
|
|
}
|