gpt4 book ai didi

java - 如何从 Commercetools 平台中的唯一 ID 获取类别名称?

转载 作者:行者123 更新时间:2023-11-30 08:06:12 24 4
gpt4 key购买 nike

我试图在 Commercetools 平台中获取产品所属的所有类别的名称。

我可以通过以下调用获取与产品关联的每个类别的唯一 ID:

final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent();
ProductProjectionQuery q = query.withLimit(450);

try {
PagedQueryResult<io.sphere.sdk.products.ProductProjection> pagedQueryResult = client.execute(q).toCompletableFuture().get();
List<io.sphere.sdk.products.ProductProjection> products = pagedQueryResult.getResults();

//createDocument(products.get(0).getMasterVariant(), request);

for (io.sphere.sdk.products.ProductProjection product : products) {
String categoryId = product.getCategories().iterator().next().getId();
//createDocument(product.getMasterVariant(), request);
}
}

虽然有了 categoryId,但我不确定如何访问类别名称。我认为 obj 属性可能允许我深入了解类别,但 obj 变量似乎总是 null

最佳答案

obj 变量为空,因为您还没有展开引用。除非您明确要求,否则所有引用都将为空以提高性能。为了扩展它,您可以使用此代码:

// Query products
final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent()
.withExpansionPaths(product -> product.categories()) // Request to expand categories
.withLimit(450);
final List<ProductProjection> products = client.execute(query).toCompletableFuture().join().getResults();

for (ProductProjection product : products) {
final List<LocalizedString> categoryLocalizedNames = product.getCategories().stream()
.map(categoryRef -> categoryRef.getObj().getName())
.collect(toList());
// Do something with categoryLocalizedNames
}

但我强烈建议您将类别缓存在 CategoryTree 实例中并从中获取名称,否则性能会因扩展每个产品的所有类别而受到很大影响。这是代码:

// Query all categories and put them in a CategoryTree
final CategoryQuery queryAllCategories = CategoryQuery.of().withLimit(500);
final List<Category> allCategories = client.execute(queryAllCategories).toCompletableFuture().join().getResults();
final CategoryTree categoryTree = CategoryTree.of(allCategories);

// Query products
final ProductProjectionQuery query = ProductProjectionQuery.ofCurrent().withLimit(500);
final List<ProductProjection> products = client.execute(query).toCompletableFuture().join().getResults();

for (ProductProjection product : products) {
final List<LocalizedString> categoryLocalizedNames = new ArrayList<>();
product.getCategories().forEach(categoryRef -> {
final Optional<Category> categoryOpt = categoryTree.findById(categoryRef.getId());
if (categoryOpt.isPresent()) {
categoryLocalizedNames.add(categoryOpt.get().getName());
}
});
// Do something with categoryLocalizedNames
}

当然,这意味着您还必须找到一种解决方案,使缓存的类别在更改时失效。

关于java - 如何从 Commercetools 平台中的唯一 ID 获取类别名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com