javascriptrelationshipprismaprisma2

Explicit many to many relation prisma


I have these 3 prisma models,

model user {
  id                        String                 @id @default(cuid())
  createdAt                 DateTime               @default(now())
  updatedAt                 DateTime               @default(now())
  courses                   userOnCourse[]
}

model course {
  id                      String                         @id @default(cuid())
  createdAt               DateTime                       @default(now())
  updatedAt               DateTime                       @default(now())
  users                   userOnCourse[]
  title                   String
  description             String
}

model userOnCourse {
  createdAt     DateTime    @default(now())
  user          user        @relation(fields: [userId], references: [id])
  userId        String
  course        Course      @relation(fields: [courseId], references: [id])
  courseId      String

  @@id([userId, courseId])
}

It's a many-to-many relation where one user can have many courses and one course can have many users, for referencing the explicit m-m relation I created another model names userOnCourse.

I am struggling to pass the reference of courseId into the userOnCourse model, I want to connect the course in conjunction with userid into that model but as it's created on runtime it seems not possible to pass the courseId on compile time.

Here is the code, Assume we already have user data when creating a course, How to pass the courseId that has been creating on run-time, and make a connection.

I am following this reference from prisma docs.

const createCourse = await prisma.course.create({
            data: {
                title: courseData.title,
                description: courseData.description,
                users: {
                    connect: {
                        userId_courseId: {
                            userId: user.id,
                            courseId: ?? // That is where the problem is, how can i add the coursesId?
                        },
                    },
                },
            },
        });

Solution

  • What you need is create and not connect. You need to create a new entry in the many-to-many table mapping a User with the Course. So you need to create that entry.

    The code would be:

    await prisma.course.create({
        data: {
          description: 'des',
          title: 'title',
          users: { create: { userId: user.id } },
        },
    })