What is the best way to link newly added product to a category?

After 7.4.2, Product category link have been moved to Category. So whats the best way to link a newly imported product to a category.

It seems, adding to product links of category and updating category results a rebuild index of all products in that category. Is there any other better way?

Litium version: 7.4.3

Your available option is to do as you’re describing, adding the product to the .ProductLinks collection of the category.

However, when testing I’m not seeing indexing logged for all products in the category, only the one just updated.

Could you share the code for AddProductToCategory? May be, when I’m doing the sort index might be changing(just a thought)

Assuming that the link can’t already exist and that you have baseProduct and variant.

var category = _categoryService.Get(categorySystemId).MakeWritableClone();
var link = new CategoryToProductLink(baseProduct.SystemId);
link.ActiveVariantSystemIds(variant.SystemId);
category.ProductLinks.Add(link);

using (_securityContextService.ActAsSystem())
{
	_categoryService.Update(category);
}

You can also add all variants at once, something like

category.ProductLinks.Add(new CategoryToProductLink(baseProduct.SystemId)
{
	ActiveVariantSystemIds = new HashSet<Guid>(_variantService.GetByBaseProduct(baseProduct.SystemId).Select(x => x.SystemId))
});
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.