diff --git a/src/service/product.service.ts b/src/service/product.service.ts index 487773b..71bad04 100644 --- a/src/service/product.service.ts +++ b/src/service/product.service.ts @@ -210,12 +210,14 @@ export class ProductService { // 解析属性输入(中文注释:按 id 或 dictName 创建/关联字典项) const resolvedAttributes: DictItem[] = []; for (const attr of attributes) { - if (!attr?.dictName) throw new Error('属性项缺少字典名称'); let item: DictItem | null = null; if (attr.id) { + // 中文注释:如果传入了 id,直接查找字典项并使用,不强制要求 dictName item = await this.dictItemModel.findOne({ where: { id: attr.id }, relations: ['dict'] }); if (!item) throw new Error(`字典项 ID ${attr.id} 不存在`); } else { + // 中文注释:当未提供 id 时,需要 dictName 与 title/name 信息创建或获取字典项 + if (!attr?.dictName) throw new Error('属性项缺少字典名称'); const titleOrName = attr.title || attr.name; if (!titleOrName) throw new Error('新建字典项需要提供 title 或 name'); item = await this.getOrCreateAttribute(attr.dictName, titleOrName, attr.name); @@ -315,17 +317,22 @@ export class ProductService { }; for (const attr of updateProductDTO.attributes) { - if (!attr?.dictName) throw new Error('属性项缺少字典名称'); let item: DictItem | null = null; if (attr.id) { + // 中文注释:当提供 id 时直接查询字典项,不强制要求 dictName item = await this.dictItemModel.findOne({ where: { id: attr.id }, relations: ['dict'] }); if (!item) throw new Error(`字典项 ID ${attr.id} 不存在`); } else { + // 中文注释:未提供 id 则需要 dictName 与 title/name 信息 + if (!attr?.dictName) throw new Error('属性项缺少字典名称'); const titleOrName = attr.title || attr.name; if (!titleOrName) throw new Error('新建字典项需要提供 title 或 name'); item = await this.getOrCreateAttribute(attr.dictName, titleOrName, attr.name); - } - replaceAttr(attr.dictName, item); + } + // 中文注释:以传入的 dictName 或查询到的 item.dict.name 作为替换键 + const dictKey = attr.dictName || item?.dict?.name; + if (!dictKey) throw new Error('无法确定字典名称用于替换属性'); + replaceAttr(dictKey, item); } product.attributes = nextAttributes;