2

Suppose I have some entries in a section called 'product' that are related to a category call 'brand' - I know I can get the brands that are related to each product that match a search term using GraphQL like so:

query Query($searchTerm: String) {
  entries(search: $searchTerm, section: "product") {
    ... on product_product_Entry {
      brand {
        id
      }
    }
  }
}

Which returns something like this:

{
  "data": {
    "entries": [
      {
        "brand": [
          {
            "id": "3"
          }
        ]
      },
      {
        "brand": [
          {
            "id": "5"
          }
        ]
      },      
      {
        "brand": [
          {
            "id": "3"
          }
        ]
      },
      ...

What I'm looking to do is get all the brands that are related to the products matching the search, but obviously if I use the above query then the response will get very big very quick. Is it possible to get just the distinct brand id values returned from the above GraphQL query? Or am I better off making a module with a controller action and querying the database that way?

2 Answers 2

3

You can run a categories query and pass it your product id(s) as well as the category group id (though that's not necessary) to fetch all categories related to your products.

The query:

query getRelatedBrands($relatedTo: [QueryArgument] = "", $groupId: [QueryArgument] = "") {
  categories(groupId: $groupId, relatedTo: $relatedTo) {
    id
  }
}

and the variables:

{
  "relatedTo": [13306, 13638],
  "groupId": [1]
}

Which would return:

{
  "data": {
    "categories": [
      {
        "id": "3"
      },
      {
        "id": "234"
      }
    ]
  }
}
1
  • Thanks for your answer. The issue with doing it this way, as far as I can tell, is that if you were to search over many products (e.g. thousands) you are going to end up having huge GraphQL requests - unless I am missing something?
    – Seb Jones
    Commented Jan 27, 2021 at 16:00
1

If I understand correctly you are searching for products with a $searchTerm query variable and you want a separate list of the unique brands related to those products.

You could use a categories GraphQL query with the relatedToEntries argument. Pass in search: $searchTerm like you would with an element query.

query Query($searchTerm: String) {
  brands: categories(group: "brand", relatedToEntries: [{section: "product", search: $searchTerm}] {
    id
  }
}

Should return a list like this:

{
  "data": {
    "brands": [
      {
        "id": "3"
      },
      {
        "id": "5"
      },
      {
        "id": "19"
      },
      ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.