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?

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
    Jan 27 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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