Miloslavc
Miloslavc

Reputation: 127

One-to-many and may-to-many relation between two prisma model

I am working on a side project and I came to an issue that I'm not sure how to solve. I have created two models, one for User and one for Project. The relation between them is many-to-many, as many users can have many projects, but i would also like to add a createdBy to the Project model, and this should be one-to-one as each project can only have one user who creates it. This is how my models are looking:

model User {
  id            String         @id @default(cuid())
  name          String?
  email         String?        @unique
  emailVerified DateTime?
  image         String?
  createdAt     DateTime       @default(now())
  updatedAt     DateTime       @updatedAt
  accounts      Account[]
  sessions      Session[]
  projects      Project[]
  Project       Project[]      @relation("userId")
}

model Project {
  id             Int          @id @default(autoincrement())
  createdAt      DateTime     @default(now())
  name           String
  favourite      Boolean      @default(false)
  archived       Boolean      @default(false)
  users          User[]
  about          String?
  archivedAt     String?
  deletedAt      String?
  createdBy      User         @relation("userId", fields: [userId], references: [id])
  userId         String
}

The error that is getting from prisma migrate dev is

Step 1 Added the required column userId to the Project table without a default value. There are 2 rows in this table, it is not possible to execute this step.

Not sure what I am doing wrong as am pretty much a db modeling novice. Any help would be appreciated.

Upvotes: 0

Views: 1327

Answers (1)

Somsubhra Das
Somsubhra Das

Reputation: 166

To achieve Many-to-Many with One-To-Many you need to set your schema.prisma file like:

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt

  projects Project[]

  userProjects UserProjects[]
}

model Project {
  id         Int      @id @default(autoincrement())
  createdAt  DateTime @default(now())
  name       String
  favourite  Boolean  @default(false)
  archived   Boolean  @default(false)
  about      String?
  archivedAt String?
  deletedAt  String?

  createdBy User   @relation(fields: [user_id], references: [id])
  user_id   String

  projectUsers UserProjects[]
}

model UserProjects {
  project    Project @relation(fields: [project_id], references: [id])
  project_id Int
  user       User    @relation(fields: [user_id], references: [id])
  user_id    String

  @@id([project_id, user_id])
}

It should migrate successfully.

Upvotes: 3

Related Questions