How to Get Related Products Using GraphQL Query in Magento 2
How to Get Related Products Using GraphQL Query in Magento 2
Magento 2's GraphQL API enables developers to fetch product data seamlessly, including related products. This guide provides a comprehensive overview of how to retrieve related products for a specific item using a GraphQL query, with practical examples and detailed explanations.
Table Of Content
- What Are Related Products in Magento 2?
- Prerequisites: Understanding Product Query in Magento GraphQL
- GraphQL Query to Fetch Related Products
- Practical Example: Display Related Products on the Product Page
- Adding Custom Fields to Related Products Query
- Error Handling and Empty Results
- Comparing Related Products with Up-Sell and Cross-Sell Products
- Conclusion
- FAQs
What Are Related Products in Magento 2?
Related products in Magento 2 are additional or alternative items displayed on product pages to encourage customers to explore more options. These products are chosen to complement or enhance the customer's shopping experience by providing helpful suggestions. Implementing related products can boost sales, increase engagement, and improve customer satisfaction.
Benefits of Using Related Products
Related products in Magento 2 provide both customers and store owners with several advantages. Here’s how they make a difference:
Feature | Benefit |
---|---|
Increased Cross-Selling | Encourages customers to explore and add complementary products to their carts. |
Enhanced User Experience | Provides relevant, helpful product recommendations tailored to the customer’s preferences. |
Higher Average Order Value | Motivates customers to purchase additional items, increasing the overall purchase value. |
Improved Engagement | Keeps customers browsing longer, creating a more engaging shopping journey. |
Streamlined Navigation | Simplifies the shopping process by showcasing related items directly on the product page. |
Personalization | Allows for dynamic, personalized recommendations based on customer behavior and preferences. |
Examples of Related Products Usage
Upselling Accessories:
A customer viewing a smartphone might see cases, chargers, or screen protectors listed as related products.
Alternatives for Consideration:
If a product is out of stock, related products can offer alternative choices, keeping the customer on your site.
Seasonal Recommendations:
A winter jacket might display related products such as gloves, scarves, or boots.
How to Configure Related Products in Magento 2
Access the Admin Panel:
Go to Catalog > Products and select the product you want to edit.
Navigate to Related Products Section:
Scroll to the Related Products, Up-Sells, and Cross-Sells section.
Add Related Products:
Use the search tool to find and add relevant items as related products.
Save Changes:
Click Save to apply your changes.
Tips for Effective Use of Related Products
- Analyze Customer Behavior: Use analytics to identify frequently bought items and group them as related products.
- Leverage Automation Tools: Magento extensions can automate the selection of related products for efficiency and accuracy.
- Test and Optimize: Regularly test different combinations of related products to determine what resonates best with customers.
By implementing related products strategically, you not only enhance the shopping experience but also unlock the potential for greater sales and customer loyalty.
Prerequisites: Understanding Product Query in Magento GraphQL
Before you dive into fetching related products, it's essential to have a solid understanding of the foundational concepts of Product Queries in Magento GraphQL. This knowledge will enable you to effectively customize, extend, and optimize your queries for related products.
Key Concepts to Understand:
GraphQL Basics:
- Learn how GraphQL queries and mutations work.
- Understand query structure, including fields, arguments, and nested relationships.
Magento Product Schema:
- Familiarize yourself with the Magento GraphQL schema, particularly the
products
field. - Explore key attributes like
sku, name, price, media_gallery,
andstock_status
.
Filter Conditions:
- Understand how to apply filters to queries, such as
eq
(equals),like
,gt
(greater than), orin
. - Example: Retrieve products based on SKU or price range.
Pagination:
- Learn to manage large datasets using
pageSize
andcurrentPage
for optimal performance.
Relationships and Associations:
- Explore how product relationships, like upsells, cross-sells, and related products, are structured in the schema.
- Understand how to retrieve associated product data efficiently.
Additional Recommendations:
- GraphQL Testing Tools: Use tools like GraphiQL or Postman to test and debug queries.
- Magento Documentation: Leverage Magento’s official GraphQL API documentation for in-depth schema references and query examples.
- Basic Magento Admin Knowledge: Understand how related products, upsells, and cross-sells are configured in the Magento admin panel, as this directly impacts the query results.
Why These Prerequisites Matter:
- Customization: Knowing the schema helps you tailor queries to include only the data you need, improving performance
- Scalability: Familiarity with filters and pagination ensures your queries are efficient, even for large catalogs.
- Optimization: Understanding relationships and associations allows you to create complex, meaningful queries that enhance the user experience.
By mastering these prerequisites, you'll be well-equipped to fetch and customize related product data, ensuring your queries align with your business needs and Magento's capabilities.
GraphQL Query to Fetch Related Products
The following GraphQL query demonstrates how to retrieve related products for a specific product using its SKU. This query is highly customizable and can be extended to include additional attributes or filters as required.
Example Query:
{
products(filter: { sku: { eq: "24-MB01" } }) {
items {
id
name
related_products {
id
sku
name
stock_status
short_description {
html
}
url_key
image {
url
label
}
special_price
price_range {
minimum_price {
final_price {
value
currency
}
}
maximum_price {
final_price {
value
currency
}
}
}
}
}
}
}
Explanation of Query Components
Field | Description |
---|---|
products | Fetches product data based on specified filters like SKU. |
related_products | Retrieves the related products associated with the specified item. |
stock_status | Indicates the availability of the product (e.g., IN_STOCK or OUT_OF_STOCK). |
short_description.html | Provides an HTML-formatted brief description of the product. |
url_key | Generates the product's URL key for easy navigation on the storefront. |
image.url | Fetches the URL of the primary product image for visual representation. |
image.label | Provides an alternate text label for the image, enhancing accessibility and SEO. |
special_price | Displays any promotional or discounted price available for the product. |
price_range | Includes minimum and maximum prices for products, displayed in various currencies. |
final_price.value | Shows the actual price the customer pays, including discounts if applicable. |
final_price.currency | Specifies the currency in which the product is priced (e.g., USD, EUR). |
Sample Output of the Query
{
"data": {
"products": {
"items": [
{
"id": 1,
"name": "Joust Duffle Bag",
"related_products": [
{
"id": 2,
"sku": "24-MB02",
"name": "Push It Messenger Bag",
"stock_status": "IN_STOCK",
"short_description": {
"html": "<p>Compact and lightweight bag for daily use.</p>"
},
"url_key": "push-it-messenger-bag",
"special_price": 45,
"price_range": {
"minimum_price": {
"final_price": {
"value": 50,
"currency": "USD"
}
},
"maximum_price": {
"final_price": {
"value": 50,
"currency": "USD"
}
}
}
}
]
}
]
}
}
}
Additional Customizations
Filter by Stock Status:
Add a filter to retrieve only in-stock related products:
related_products(filter: { stock_status: { eq: "IN_STOCK" } })
Pagination for Related Products:
If a product has many related items, use pagination:
related_products(pageSize: 5, currentPage: 1) {
id
name
}
Fetch Reviews and Ratings:
Include customer reviews and ratings to enhance the query:
rating_summary
review_count
Include Custom Attributes:
Add attributes like brand, material, or custom fields for richer data:
custom_attributes {
attribute_code
value
}
Why Use This Query?
- Enhanced User Experience: Provides detailed and relevant product recommendations to customers.
- Increased Engagement: Displays visually rich and helpful product data, including images and descriptions.
- Boosted Sales: Helps customers explore complementary items, driving higher average order value.
- Customizability: Offers flexibility to tailor the query to your specific business needs.
This query serves as a robust foundation for fetching and displaying related products effectively, making it an integral part of your Magento GraphQL strategy.
Practical Example: Display Related Products on the Product Page
Follow these steps to dynamically display related products on the product page:
1. Assign Related Products
- Navigate to Admin Panel > Catalog > Products.
- Select a product you want to associate with others.
- Scroll down to Related Products, Up-Sells, and Cross-Sells.
- Click Add Related Products and choose the desired products.
- Save your changes to update the product relationships.
2. Fetch Related Products via GraphQL
Use the following GraphQL query to retrieve the related products dynamically:
{
"products": (filter: { sku: { eq: "your-product-sku" } }) {
items {
id
name
related_products {
id
name
sku
stock_status
url_key
special_price
price_range {
minimum_price {
final_price {
value
currency
}
}
}
}
}
}
}
Replace "your-product-sku"
with the SKU of the product you want to query.
3. Render Related Products on the Frontend
- Customize your product page template to display the fetched related products.
- Use a frontend framework like Knockout.js or custom JavaScript to render the data dynamically.
By following these steps, you can seamlessly integrate and display related products on the product page, improving cross-selling opportunities and enhancing the customer shopping experience.
Adding Custom Fields to Related Products Query
Enhancing your related products query with additional fields like product images, ratings, and reviews can significantly improve the user experience and provide shoppers with more information.
Example Query with Additional Fields
Here’s an enhanced GraphQL query to fetch related products with custom fields for product images, ratings, and reviews:
{
"products": (filter: { sku: { eq: "24-MB01" } }) {
items {
related_products {
id
sku
name
stock_status
short_description {
html
}
url_key
special_price
price_range {
minimum_price {
final_price {
value
currency
}
}
maximum_price {
final_price {
value
currency
}
}
}
media_gallery {
url
label
}
rating_summary
review_count
}
}
}
}
Explanation of New Fields
Field | Description |
---|---|
media_gallery |
Fetches all product images and their labels. |
rating_summary |
Displays the average rating (typically shown as stars). |
review_count |
Provides the total number of customer reviews for the product. |
Error Handling and Empty Results
When querying for related products, it is important to handle cases where no related products are assigned or the query encounters an error. The related_products
field may return an empty array if no related products exist, or an error may occur during the request. Handling these scenarios gracefully is essential for a smooth user experience.
Example 1: Handling Empty Results
If the queried product does not have related products assigned, the related_products
field will return an empty array. Here's how you can handle that scenario in your code:
if (relatedProducts.length === 0) {
console.log("No related products available.");
// Optionally, display a message to the user on the frontend
showNoRelatedProductsMessage();
} else {
renderRelatedProducts(relatedProducts);
}
Example 2: Handling GraphQL Query Errors
GraphQL queries can sometimes fail due to network issues, malformed queries, or other reasons. It's important to catch errors and inform the user about the issue. Here's an example of how to handle GraphQL query errors:
fetchGraphQLQuery(query)
.then(response => {
if (response.errors) {
console.error("Error fetching related products:", response.errors);
showErrorMessage("An error occurred while loading related products.");
} else {
const relatedProducts = response.data.products.items[0].related_products;
if (relatedProducts.length === 0) {
console.log("No related products available.");
showNoRelatedProductsMessage();
} else {
renderRelatedProducts(relatedProducts);
}
}
})
.catch(error => {
console.error("Network error:", error);
showErrorMessage("Unable to fetch related products. Please try again later.");
});
Example 3: Optimizing User Experience with Loading Indicators
To improve the user experience, consider adding a loading spinner or indicator while the related products are being fetched:
showLoadingIndicator();
fetchGraphQLQuery(query)
.then(response => {
hideLoadingIndicator();
if (response.errors) {
console.error("Error fetching related products:", response.errors);
showErrorMessage("An error occurred while loading related products.");
} else {
const relatedProducts = response.data.products.items[0].related_products;
if (relatedProducts.length === 0) {
console.log("No related products available.");
showNoRelatedProductsMessage();
} else {
renderRelatedProducts(relatedProducts);
}
}
})
.catch(error => {
hideLoadingIndicator();
console.error("Network error:", error);
showErrorMessage("Unable to fetch related products. Please try again later.");
});
Tips for Improved Error Handling:
- Clear Error Messages: Use clear and simple error messages to help users understand the issue.
- Network Retry: If the error is network-related, consider implementing a retry mechanism to reattempt fetching related products.
- Fallback Content: Always provide fallback content or alternatives (like showing popular products) if related products are unavailable.
By following these practices, you can ensure a better and smoother user experience, even when related products are missing or errors occur during the GraphQL request.
Comparing Related Products with Up-Sell and Cross-Sell Products
Type | Purpose | Display Location |
---|---|---|
Related Products | These products are complementary to the main product, helping customers discover items that are similar or enhance the use of their purchase. | Displayed on the Product Detail Page to encourage customers to explore additional items that go well with their current selection. |
Up-Sell Products | These are higher-priced alternatives to the original product, designed to encourage customers to upgrade their purchase by choosing a premium option. | Typically shown on the Product Detail Page, near the main product to prompt a better deal or more advanced version. |
Cross-Sell Products | These products are frequently bought together or complement the customer's current purchase. Their goal is to suggest items that work well alongside the product being considered. | Shown on the Cart Page or Checkout Page, offering additional products that complement or enhance the customer's order, increasing overall sales. |
Key Differences Between the Three Types:
Related Products:
- Purpose: Focuses on enhancing the user’s shopping experience by suggesting complementary items.
- Example: For a "Joust Duffle Bag," related products might include other types of bags, such as a "Push It Messenger Bag."
- Impact: Encourages customers to explore more options that are similar to what they’re already interested in.
Up-Sell Products:
- Purpose: Encourages customers to make a more expensive purchase by showcasing higher-end versions of the product.
- Example: An up-sell for the "Joust Duffle Bag" could be a more premium duffle bag with better material or features at a higher price.
- Impact: Increases the overall order value by convincing the customer to opt for a more expensive option.
Cross-Sell Products:
- Purpose: Focuses on items that complement the current cart, increasing the average cart value by encouraging customers to buy additional products that are often bought together.
- Example: For a duffle bag, cross-sells could include "travel accessories" like luggage tags, passport holders, or a matching travel pillow.
- Impact: Increases the total cart value by suggesting products that the customer may not have thought of but would likely find useful in conjunction with their current purchase.
By understanding the different types of products you can recommend (related, up-sell, and cross-sell), you can better strategize how to present these suggestions in the right context and at the right time.
Tip
To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!
Conclusion
In conclusion, fetching and displaying related products using GraphQL queries in Magento 2 is a highly effective way to enhance the shopping experience and boost sales. By utilizing Magento's powerful GraphQL API, you can dynamically retrieve related products and display them on the product detail pages, offering your customers relevant suggestions that complement their current selections.
The process involves setting up the right GraphQL queries, handling various response scenarios (including empty or error responses), and seamlessly integrating the fetched data into your frontend. With additional fields like product images, ratings, and prices, you can make these related products more appealing and informative, encouraging customers to explore more options.
Moreover, by handling related, up-sell, and cross-sell products strategically, you can create a more personalized and engaging shopping journey. This approach not only improves customer satisfaction but also maximizes the potential for increasing average order value and conversion rates.
Ultimately, using GraphQL queries to fetch related products in Magento 2 is a powerful tool that, when implemented correctly, can significantly enhance the overall eCommerce experience and drive business growth.
FAQs
What is GraphQL in Magento 2?
GraphQL is a query language for your API that allows flexible and efficient data fetching. In Magento 2, it is used to retrieve product information, including related products, up-sells, and cross-sells.
How do I fetch related products using GraphQL in Magento 2?
To fetch related products, you need to use the appropriate GraphQL query that targets the product's related products. This involves querying the products and specifying the related_products field in your query.
Can I fetch multiple types of products (related, up-sell, cross-sell) using a single query in Magento 2?
Yes, you can fetch related products, up-sell products, and cross-sell products by expanding the appropriate fields in a single GraphQL query. These fields can be included together under the same product query to display multiple product types.
What fields can be included when fetching related products in Magento 2?
You can include fields such as product name, SKU, stock status, price, media gallery (images), rating summary, review count, and special price when fetching related products using GraphQL.
How can I handle errors when fetching related products with GraphQL?
Handle errors by checking if the GraphQL response contains errors. If there are errors, display an appropriate message to the user and log the issue for further investigation.
What happens if no related products are available in Magento 2?
If no related products are found, the related_products field will return an empty array. You can handle this gracefully by showing a message like "No related products available" to the user.
How can I display related products dynamically on the frontend?
After fetching the related products through GraphQL, you can use JavaScript or a template engine to dynamically render the products in your frontend design, either through a product carousel or a static list.
What is the difference between related products, up-sell, and cross-sell products?
Related products complement the current product, up-sell products are premium alternatives, and cross-sell products are items frequently bought together or that enhance the current purchase.
How do I set up related products in Magento 2?
To set up related products, go to the product page in the Admin Panel, find the Related Products section, and add products that complement the current item. Save the changes to assign related products to the product.
Can I add custom attributes to the related products query in Magento 2?
Yes, you can customize the GraphQL query to include additional fields or attributes like product custom attributes, custom prices, or other relevant data, as long as they are defined in your product schema.
How can I optimize the performance of related product queries in Magento 2?
Optimize the performance by limiting the number of related products fetched, using caching techniques for GraphQL responses, and ensuring that only necessary fields are included in the query to reduce the load on the server.
What should I do if related products do not show up on the product page?
If related products are not showing up, check if the GraphQL query is correct, ensure that related products are assigned in the admin panel, and confirm that the frontend code is correctly handling the GraphQL response.