Search code examples
databasepostgresqlormforeign-keysprisma

relating tables with the ORM prism


Using PostgreSQL, I want to make an application that manages Daily Habits. I'm trying to make a one-to-many relationship from the User tables to Habits and Habits to the other tables.

model User {
  id           String   @id @default(uuid())
  email        String   @unique
  verify_email Boolean  @default(false)
  Habit        Habit?   @relation(fields: [habitId], references: [id])
  habitId      String[] @unique

  @@index([habitId])
  @@map("user")
}

model Habit {
  id         String          @id @default(uuid())
  title      String
  created_at DateTime
  user       User[]
  dayHabits  DayHabit[]
  weekDays   HabitWeekDays[]

  @@map("habits")
}

Creating habits, when there is more than one Habit, the new one overwrites the previous one.

rest of code


Solution

  • Creating one-to-many relations in Prisma is pretty straightforward as can be seen in the documentation

    An example code of one-to-many relation between user and habit is

    model User {
      id           String   @id @default(uuid())
      email        String   @unique
      verify_email Boolean  @default(false)
      habit        Habit[]   
      @@index([id])
      @@map("user")
    }
    
    model Habit {
      id         String          @id @default(uuid())
      title      String
      created_at DateTime
      user       User @relation(fields: [userId], references: [id])
      userId      String
      // dayHabits  DayHabit[]
     // weekDays   HabitWeekDays[]
    
      @@map("habits")
    }
    

    Also, you didn't specify what you are trying to achieve with these fields dayHabits and weekDays.