Fetching Unique Categories related to Entries via GraphQL 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: &quot;product&quot;) {
    ... on product_product_Entry {
      brand {
        id
      }
    }
  }
}

Which returns something like this:
{
  &quot;data&quot;: {
    &quot;entries&quot;: [
      {
        &quot;brand&quot;: [
          {
            &quot;id&quot;: &quot;3&quot;
          }
        ]
      },
      {
        &quot;brand&quot;: [
          {
            &quot;id&quot;: &quot;5&quot;
          }
        ]
      },      
      {
        &quot;brand&quot;: [
          {
            &quot;id&quot;: &quot;3&quot;
          }
        ]
      },
      ...

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?
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] = &quot;&quot;, $groupId: [QueryArgument] = &quot;&quot;) {
  categories(groupId: $groupId, relatedTo: $relatedTo) {
    id
  }
}

and the variables:
{
  &quot;relatedTo&quot;: [13306, 13638],
  &quot;groupId&quot;: [1]
}

Which would return:
{
  &quot;data&quot;: {
    &quot;categories&quot;: [
      {
        &quot;id&quot;: &quot;3&quot;
      },
      {
        &quot;id&quot;: &quot;234&quot;
      }
    ]
  }
}