2

I am using GraphQl API in an Amplify project and having some difficulty understanding how to model a many to many relationship between users. I get how to add a join table between two other tables. But now sure how to do it for the same table.
This is what I have but I'm almost certain it's not correct. I want each user to be able to add other Users as 'relations':

type User
    @model
    @auth(rules: [{ allow: owner, operations: [create, delete, update] }]) {
    id: ID!
    cognitoId: ID!
    username: String!
    registered: Boolean
    contacts: [UserContacts] @connection(keyName: "byContact", fields: ["id"])
    contactOfOtherUsers: [UserContacts] @connection(keyName: "byContact2", fields: ["id"])
}

type UserContacts
    @model
    @auth(rules: [{ allow: owner, operations: [create, delete, update] }])
    @key(name: "byContact", fields: ["userID", "contactID"])
    @key(name: "byContact2", fields: ["contactID", "userID"]) {
    id: ID!
    userID: ID!
    contactID: ID!
    user: User! @connection(fields: ["userID"])
    contact: User! @connection(fields: ["contactID"])
}

I'm pretty new to Amplify and not really sure what approach to take.

What seems very wrong to me is the contactOfOtherUsers field in User. It is redundant but not sure how else to link the join table.

alionthego
  • 8,508
  • 9
  • 52
  • 125

1 Answers1

0

Maybe too late but this might work. Disclaimer: This would apply to Amplify GraphQL Transformer v1, which still works but it is deprecated as it was replaced by GraphQL Transformer v2

type User
    @model
    @auth(rules: [{ allow: owner}]) {
    id: ID!
    cognitoId: ID!
    username: String!
    registered: Boolean
    contacts: [UserContact] @connection(keyName: "byContact", fields: ["id"])
}

type UserContact
  @model
  @auth(
    rules: [
      { allow: owner }
      {
        allow: owner
        ownerField: "contacts"
        operations: [update, delete, read]
      }
    ]
  ) @key(name: "byContact", fields: ["contactOneID", "contactTwoID"]){
  id: ID!
  contactOneID: ID! 
  contactTwoID: ID!
  contactOne: User! @connection(fields: ["contactOneID"])
  contactTwo: User! @connection(fields: ["contactTwoID"])
  contacts: [ID]
}
Leonardo
  • 3
  • 2