How to Create a Product Relationship
You can use the Catalog API to create relationships with a product. You can create product-to-product relationships or product-to-category relationships. These relationships can be to products and categories in the same catalog or in different catalogs.
Relationships are widely used to "cross-sell" products. That is, you can define a relationship between two products that identifies products similar to the one a customer is buying. For example, in a product-to-product relationship, if you have a user who buys a movie, you may want to offer the user the soundtrack to the movie. To do this you would create a relationship between the movie product and the soundtrack product.
You can create relationships between a single product and multiple products or categories. The relationshipName parameter does not have to be unique.
You can also create multiple relationships between a single product and a single target item. In this case the relationshipName must be unique.
To create a relationship to a product
- Use one of the AddRelationshipToProduct methods on the CatalogItem object.
To remove a relationship to a product
- Use the RemoveRelationshipToProduct method on the CatalogItem object.
To access the products related to a product or category
Use the RelatedProducts property on the CatalogItem object to get a dataset that contains the related products for the specified product. Use this property to access the products related to either a product or a category.
Iterate through the dataset to access the individual relationships and products.
Example
This example adds a relationship "Jungle print fabric" between a product and a target product. It then accesses the related products and iterates through them, displaying the relationship name. It then deletes the relationship to the target product.
private static void CreateandDeleteProductRelationships(CatalogContext context, string productId, string targetId, ProductCatalog catalog)
{
// Create a relationship between a product and a target product.
CatalogItem catalogItem = catalog.GetProduct(productId);
catalogItem.AddRelationshipToProduct(catalog.Name, targetId, "Jungle print fabrics", "All products made of jungle print fabric");
catalogItem.Save();
// Get the products related to this product.
CatalogRelationshipsDataSet relatedProducts = catalogItem.RelatedProducts;
foreach (CatalogRelationshipsDataSet.CatalogRelationship relatedProduct in relatedProducts.CatalogRelationships)
{
// Display the relationship name.
Console.WriteLine(relatedProduct.RelationshipName);
// Delete the relationships on this product.
catalogItem.RemoveRelationshipToProduct(catalog.Name, relatedproduct.TargetProductId, relatedProduct.RelationshipName);
}
// Save the changes.
catalogItem.Save();
}