Home App Docs Blog Github

Using graphql to query model with 'foreign keys'

Hi,

I’m working on a POC with builder.io to build a CMS pipeline with articles linked to brands and/or categories. I’m trying to get all articles with a ‘foreign key’ to a brand or a category but can’t figure out the graphql query. I have the following setup :

  • model Brand
  • model Category
  • model Article with
    field ‘categories’ : list of type reference to model Category
    field ‘brands’ : list of type reference to model Brand

I have tried the following query :

query {
article(query: {data: {brands: “{’$in’: [‘xxxxxxxxxxxxxxxxxxxxxxxxx’]}”} }){
data {
title
summary
paragraphs
writer
brands
picture
}
}
}

but couldn’t get it to work.

I’m not sure what I’m doing wrong, any help is welcome .

Hi @stanpanza , It’s hard without seeing how the structure of the data you have configured for articles, so going to use an example here for a model, that have a list of authors, where the structure is similar to this

   "modelWithList": [
      {
        "name": "onlly johnny",
        "data": {
          "authorsList": [
            {
              "author": {
                "@type": "@builder.io/core:Reference",
                "id": "edcaddd1a70f494ba1955704cd88ca4f",
                "model": "author"
              }
            }
          ]
        }
      },
      {
        "name": "all",
        "data": {
          "authorsList": [
            {
              "author": {
                "@type": "@builder.io/core:Reference",
                "id": "ba1fb5129adf4c379424d346666cc092",
                "model": "author"
              }
            },
            {
              "author": {
                "@type": "@builder.io/core:Reference",
                "id": "edcaddd1a70f494ba1955704cd88ca4f",
                "model": "author"
              }
            }
          ]
        }
      }
    ]

Where authorsList is a list of author model references, and a graphql query that look like this :

query($query: JSONObject!) {
  // includeRefs is optional and it means to populate references values
  modelWithList(query: $query, options: { includeRefs: true }) {
    name
    data {
      authorsList
    }
  }
}

and I want to find all entries that has reference to a specific ID within the authorsList array I can do:

{
  "query": {
    "data.authorsList.author.id": "ba1fb5129adf4c379424d346666cc092"
  }
}

If I wanted to query the content with authorsList that contain any value from a list of ids, or compose custom queries on the list elements, you can use here $elemMatch

{
  "query": {
    "data.authorsList": {
      "$elemMatch": {
        "author.id": {
          "$in": [
            "first-value",
            "some-other-value"
          ]
        }
      }
    }
  }
}

Hope this helps