1

I have two models, a User and a UserProfile model. When a user registers on my site, it should create a User and User Profile record at the same time.

model User {
  id       Int    @id @default(autoincrement())
  username String @unique @default("user")
  email    String    @unique
  hashed_password String
  role     Role      @relation(fields: [roleId], references: [id]) // Fields: PK, references: FK
  roleId   Int       @default(0)
  
  profile UserProfile? @relation(fields: [profileId], references: [id], onUpdate: Cascade)
  profileId Int? @unique
  
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now()) @updatedAt
}

model UserProfile {
  id Int @id @default(autoincrement())
  user User?
  userId Int @unique
}

Currently, I create a User:

  const user = await prisma.user.create({
    data: {
      email,
      username,
      role: {
        connectOrCreate: {
          create: {
            name: ValidRoles["User"]
          },
          where: {
            id: 1
          }
        }
      },
      hashed_password: hashedPassword,
    },
  })
}

And then I create the User Profile:


  const profile = await prisma.userProfile.create({
    data: {
      userId: user.id,
    }
  })

Then, finally, I update the user record I just created, connecting the profile via UserProfile.id:

await prisma.user.update({
    where: { id: user.id },
    data: {
      profile: {
        connect: {
          id: profile.id
        }
      }
    }
  })

I feel like I could simplify this. A nested write was one idea I had:


  const user = await prisma.user.create({
    data: {
      email,
      username,
      role: {
        connectOrCreate: {
          create: {
            name: ValidRoles["User"]
          },
          where: {
            id: 1
          }
        }
      },
      hashed_password: hashedPassword,
      profile: {
        create: {
          userId: // how to self-reference this records' id?
        }
      }
    },
  })

But as you can see, userId is required. Any other idea I've had has been constrained by this, so I'd like to know if I can somehow do a nested write with self referenced ID or if there's a way to cut down the size of these queries?

T. Duke
  • 646
  • 1
  • 6
  • 17

0 Answers0