Filtering product variant by product slug and combined variant options?

Hi,
I’m trying to get the variant data by the product slug (which will be the product page params) and combined variant options from the product page query params (the ā€œunifiedā€ field represented as a single string).
Please see below my naive attempt to filter the variants associated with a particular product.
How would you recommend I go about this?


query Product($slug: String!, $unified: String!) {
  product(filter: {slug: {eq: $slug}}) {
    productTitle
    slug
    variants(filter: {unified: {eq: $unified}}) {
      unified
      variantTitle
    }
  }
}

Sorry if there’s already this information. I’ve read plenty but I’m still confused as to what is possible and how to achieve it. Thank you.

Hi @slane,

Sorry, I don’t think you can filter a model by a related item’s values :frowning:

As a workaround, maybe you can over-fetch and then filter it on the client side, like this?

First get the single product with all of its variants and their unified:

Then on the client side:

let productWithFilteredVariants = {
    ...response.data.product,
    filteredVariants: response.data.product.variants.filter(variant => variant.unified === 'Sizes')
}

// optional, just to remove the unfiltered `variants` for clarity
delete(productWithFilteredVariants.variants)
productWithFilteredVariants: {
  "id": "epY8UDOtSpOKOkgrH20I8w",
  "title": "T-shirt",
  "filteredVariants": [
    {
      "id": "Wyx7CL5EQJWXIUQJzyGNwg",
      "title": "Large",
      "unified": "Sizes"
    },
    {
      "id": "WqzfQh1gRAGcp38IhFavlw",
      "title": "Medium",
      "unified": "Sizes"
    },
    {
      "id": "bfq2xQOvTrmQaJYH_c8imA",
      "title": "Small",
      "unified": "Sizes"
    }
  ]

It’s not ideal, I know. Sorry about that!

Ah, ok. Thank you Roger. I’ve reworked my schema so that variants consume products rather than the other way round. Variants can then consume a computed string field (using the great plugin) of the product slug field. If any of that makes sense to anyone looking for a possible workaround in the future.

1 Like