简体   繁体   中英

Prisma Many-to-Many Relation

model Students {
  studentId Int      @id @default(autoincrement())
  user      User?    @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
  userId    Int?     @unique
  classCode String?
  courses   Course[]
}

model Course {
  courseId          Int        @id @default(autoincrement())
  courseName        String
  courseDescription String?
  courseInstructor  String
  classes           Classes[]
  students          Students[]
}

I have data in both tables seperately. I do not want to insert data in one and connect it to other using implicit relation. I just want to connect them in their implicit model by inserting both foreign key in that table by create or insert query using prisma.

for now their implicit created model is empty.

I want to know the query for that in prisma client.

I have made the relations between two models of many to many. I have data in both tables separately and their implicit model in empty. I just want to add the foreign in that table by myself to connect them. I want to know the query for that in prisma client.

What you need here is connect and create . based on prisma documantation you can create query like this.

To connect a student and many course:

await prisma.student.create({
  data: {
    userId: 1,
    classCode: "2"
    Course: { connect: [{ courseName: 'programming', courseDescription: "desc", courseInstructor: "Mr/Mrs" }, { courseName: 'development', courseDescription: "desc", courseInstructor: "Mr/Mrs" }] },
  },
})

To create a student and many course:

await prisma.student.create({
  data: {
    userId: 1,
    classCode: "2"
    Course: { connect: [{ courseName: 'programming', courseDescription: "desc", courseInstructor: "Mr/Mrs" }, { courseName: 'development', courseDescription: "desc", courseInstructor: "Mr/Mrs" }] },
  },
})

or you can use connectOrCreate

Reference: https://www.prisma.io/docs/guides/database/troubleshooting-orm/help-articles/working-with-many-to-many-relations

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