user2675468
user2675468

Reputation: 145

Add many to many connection in amplify graphql

I have a time consuming problem and no idea what I can test more. This is working, but I need the in Recruiter for positions an array. But then I have a many to many connection and nothing is working anymore. Is there a nice way to solve it? Here is my code:

type Position @model @auth(rules: []) {
  id: ID!
  title: String!
  candidates: [Candidate]! @connection(name: "PositionCandidates")
  interestedRecruiters: [Recruiter]! @connection(name: "PositionRecruiter")
}
type Candidate @model @auth(rules: []) {
  id: ID!
  firstname: String!
  lastname: String!
  email: AWSEmail!
  birthday: AWSDate!
  position: Position! @connection(name: "PositionCandidates")
}
type Recruiter @model @auth(rules: []) {
  id: ID!
  firstname: String!
  lastname: String!
  email: AWSEmail!
  birthday: AWSDate!
  positions: Position! @connection(name: "PositionRecruiter")
}

thanks !

Upvotes: 4

Views: 2607

Answers (1)

Engam
Engam

Reputation: 1061

To work with many-to-many connections with amplify/app sync you have to create a 'Join' table (type). You can think of the join table as a table where you store the connections.

I didn't completely understand from your example what you wanted the result to be, so I'll try to explain with an alternate example:

Lets say you have a system where multiple users can be the creators of a document, and a user also can be one of the creators of multiple documents. To accomplish this you must create three dynamoDb tables (or three types is the schema).

type User @model {
  id: ID!
  name: String
  documents: [UserDocument] @connection(name: "UserDocumentConnection")
}

type Document @model {
   id: ID!
   title: String
   content: String
   users: [UserDocument] @connection(name: "DocumentUserConnection")
}

type UserDocument @model {
   id: ID!
   user: User @connection(name: "UserDocumentConnection")
   document: Document @connection(name: "DocumentUserConnection")
}

Then you have a table containing all your users, a table containing all your Documents, and a table containing all the connections between users and documents.

So let's say you have a users that is creating a new document. Then you first create the document, then when it is created and you have received the document back from appsync with the new id of the document, then you must create a new object in the UserDocument table, containing the id of the user and the id of the document. You can then also add more users on the document by adding more items to the UserDocument table.

I hope this will help you to the correct path forwards.

Upvotes: 9

Related Questions