simonw / datasette-graphql

Datasette plugin providing an automatic GraphQL API for your SQLite databases
https://datasette-graphql-demo.datasette.io/
Apache License 2.0
100 stars 6 forks source link

Support multiple reverse foreign key relationships for a single table #32

Closed simonw closed 4 years ago

simonw commented 4 years ago

This will work by seeking out tables that have a foreign key reference back to the current table.

What about cases where a table has multiple references back? For example:

articles
--------
id
headline
body
created_by - fk to user
updated_by - fk to user

If there was only one fk to user, the users table could have a articles_list field pointing back to it.

In this case, I will instead create these two fields:

articles_created_by_list
articles_updated_by_list

So a GraphQL query could look like this:

{
  users(first: 5) {
    nodes {
      name
      articles_created_by_list(first: 5) {
        totalCount
        nodes {
          id
          title
        }
      }
      articles_updated_by_list(first: 5) {
        totalCount
        nodes {
          id
          title
        }
      }
    }
  }
}

Originally posted by @simonw in https://github.com/simonw/datasette-graphql/issues/27#issuecomment-669975859

simonw commented 4 years ago

Demo: https://datasette-graphql-demo.datasette.io/graphql/fixtures?query=%0A%7B%0A%20%20users%20%7B%0A%20%20%20%20nodes%20%7B%0A%20%20%20%20%20%20id%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20issues_by_user_list%20%7B%0A%20%20%20%20%20%20%20%20nodes%20%7B%0A%20%20%20%20%20%20%20%20%20%20id%0A%20%20%20%20%20%20%20%20%20%20title%0A%20%20%20%20%20%20%20%20%20%20updated_by%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20user%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20issues_by_updated_by_list%20%7B%0A%20%20%20%20%20%20%20%20nodes%20%7B%0A%20%20%20%20%20%20%20%20%20%20id%0A%20%20%20%20%20%20%20%20%20%20title%0A%20%20%20%20%20%20%20%20%20%20updated_by%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20user%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A

Docs: https://github.com/simonw/datasette-graphql/blob/main/examples/related_multiple.md