Search code examples
graphqlamazon-dynamodbaws-amplify

How Dynamo DB manages Many to Many relationship?


I have 2 tables User and Activity with a Many to Many relationship:

type User @model @auth(rules: [{allow: public}]) {
    id: ID!
    activities: [Activity] @manyToMany(relationName: "UserActivity")
}

type Activity @model @auth(rules: [{allow: public}]) {
    id: ID!
    users: [User] @manyToMany(relationName: "UserActivity")
}

From Dynamo DB how should I add my JSON data to connect these 2 tables?


Solution

  • The relationship @manyToMany, as documented here, is completely different from all others, it configures a "join table" between two models.

    Basically, after push your new GraphQL schema, in Dynamo DB you'll find a new table:

    type UserActivity {
      id: ID!
      userID: ID!
      activityID: ID!
      user: User!
      activity: Activity!
      createdAt: AWSDateTime!
      updatedAt: AWSDateTime!
    }
    

    Here you have to provide 2 different ID (userID and activityID) every time you want to join these 2 tables.

    So you don't have to add IDs to single tables (User, Activity) but only to the joined table (UserActivity)