Search code examples
graphqlreact-adminhasura

ReferenceManyFields (One to Many Relationship)


I am working on a project where I have to create one to many relationships which will get all the list of records referenced by id in another table and I have to display all the selected data in the multi-select field (selectArrayInput). Please help me out in this, if you help with an example that would be great. Thanks in advance.

Example:
district
id    name
1     A
2     B
3     C

block
id    district_id    name
1     1              ABC
2     1              XYZ
3     2              DEF

I am using https://github.com/Steams/ra-data-hasura-graphql hasura-graphql dataprovider for my application.


Solution

  • You're likely looking for "nested object queries" (see: https://hasura.io/docs/1.0/graphql/manual/queries/nested-object-queries.html#nested-object-queries)

    An example...

    query MyQuery {
      district(where: {id: {_eq: 1}}) {
        id
        name
        blocks {
          id
          name
        }
      }
    }
    

    result:

    {
      "data": {
        "district": [
          {
            "id": 1,
            "name": "A",
            "blocks": [
              {
                "id": 1,
                "name": "ABC"
              },
              {
                "id": 2,
                "name": "XYZ"
              }
            ]
          }
        ]
      }
    }
    

    Or...

    query MyQuery2 {
      block(where: {district: {name: {_eq: "A"}}}) {
        id
        name
        district {
          id
          name
        }
      }
    }
    

    result:

    {
      "data": {
        "block": [
          {
            "id": 1,
            "name": "ABC",
            "district": {
              "id": 1,
              "name": "A"
            }
          },
          {
            "id": 2,
            "name": "XYZ",
            "district": {
              "id": 1,
              "name": "A"
            }
          }
        ]
      }
    }
    

    Setting up the tables this way...

    blocks:

    enter image description here

    enter image description here

    enter image description here

    districts:

    enter image description here

    enter image description here

    enter image description here

    Aside: I recommend using plural table names as they are more standard, "districts" and "blocks"