简体   繁体   中英

How to create a many to many relationship in amplify datastore using schema.graphql

type StudentCourses
  @model(queries: null)
  @auth(rules: [{ allow: public }])
  @key(name: "byStudent", fields: ["studentID", "courseID"])
  @key(name: "byCourse", fields: ["courseID", "studentID"]) {
  id: ID!
  studentID: ID!
  courseID: ID!
  student: Student! @connection(fields: ["studentID"])
  course: Course! @connection(fields: ["courseID"])
}

type Course
  @model
  @auth(rules: [{ allow: public }])
  @key(name: "bySchool", fields: ["schoolID"]) {
  id: ID!
  courseName: String!
  schoolID: ID!
  students: [Student!] @connection(keyName: "byCourse", fields: ["id"])
}

type Student
  @model
  @auth(rules: [{ allow: public }])
  @key(name: "bySchool", fields: ["schoolID"]) {
  id: ID!
  studentName: String
  studentEmail: String
  sisID: Int
  schoolID: ID!
  courses: [Course!] @connection(keyName: "byStudent", fields: ["id"])
}

I followed the steps in docs to create a many to many relationship between student and courses but i keep getting this error Key byCourse does not exist for model Student even thought i created a model to connect school and courses. Thanks in advance

You need to omit keyName from Course , since in Student model, you have list of courses, so you can't really have @key directive for that.

https://docs.amplify.aws/cli-legacy/graphql-transformer/connection/#many-to-many-connections

type Course
  @model
  @auth(rules: [{ allow: public }])
  @key(name: "bySchool", fields: ["schoolID"]) {
  id: ID!
  courseName: String!
  schoolID: ID!
  students: [Student!] @connection(fields: ["id"])
}

Anyone who is upto V2 of Amplify, they can get guidance from this link https://docs.amplify.aws/cli/graphql/data-modeling/#belongs-to-relationship Updated Flow has the following changes

  • You need to add @manyToMany on both tables that are going to join
  • This will create a third table by itself and will add Queries and Mutations for it as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM