💽

【GraphQL, AWS】schema.graphqlに記載するリレーションの書き方4選

2021/07/02に公開約1,400字

何について書く?

GraphQL スキーマーを作成する際のリレーションの書き方

内容

  • 1対1(HasOne)
type One @model {
  id: ID!
  name: String!
  anotherOneID: ID!
  anotherOne: AnotherOne @connection(fields: ["anotherOneID"])
}

type AnotherOne @model {
  id: ID!
  name: String!
}
  • 1対多(HasMany)
type One @model {
  id: ID!
  name: String!
  manys: [Many]  @connection(keyName: "byOne" fields: ["iD"])
}

type Many @model {
 @key(name: "byOne", fields: ["oneID"]) {
  id: ID!
  oneID: ID!
  content: String!
}
  • 1対多に多対1を追加し双方向接続を可能にする(belongsto)
type One @model {
  id: ID!
  name: String!
  manys: [Many]  @connection(keyName: "byOne" fields: ["iD"])
}

type Many @model {
 @key(name: "byOne", fields: ["oneID"]) {
  id: ID!
  oneID: ID!
  content: String!
  one: One @connection(fields: ["oneID"])
}
  • 多対多は中間テーブル下記例(ManyAManyB)が必要
type ManyA @model
 {
  id: ID!
  manyBs: [ManyAManyB] @connection(keyName: "byMany", fields: ["id"])
  name: String
}

type ManyAManyB
@model(queries: null)
@key ( name: "byManyA", fields: [ "manyAID", "manyBID" ] )
@key ( name: "byManyB", fields: [ "manyBID", "manyAID" ] )
{
  id: ID!
  manyAID: ID!
  manyA:  ManyA! @connection(fields:["manyAID"])
  manyBID: ID
  manyB: ManyB! @connection(fields:["manyBID"])
}

type ManyB @model
{
  id: ID!
  mainBs: [ManyAManyB] @connection(keyName: "byManyB", fields: ["id"])
  name: String
}

参考サイト

https://docs.amplify.aws/cli/graphql-transformer/connection

Discussion

ログインするとコメントできます