Automatically add UUID relation on prisma create

Viewed 14628

I have a User, UserProfile and Post model in my Postgres database. The User and UserProfile depend on each other. I am trying to create a User that automatically creates a UserProfile with it, but I can't seem to find out how to automatically assume the User's ID for the UserProfile relation, I am using UUID for the User model.

Schema Models

model User {
  id             String       @id @default(uuid())
  createdAt      DateTime     @default(now())
  username       String       @unique @db.VarChar(20)
  emailEncrypted String       @unique
  emailIv        String       @unique
  password       String
  isMod          Boolean      @default(false)
  isAdmin        Boolean      @default(false)
  emailConfirmed Boolean      @default(false)
  profile        UserProfile?
}

model UserProfile {
  user     User      @relation(fields: [id], references: [id])
  id       String    @unique
  posts    Post[]
  comments Comment[]
}

model Post {
  id        String      @id @default(uuid())
  createdAt DateTime    @default(now())
  title     String      @db.VarChar(300)
  caption   String      @db.VarChar(1000)
  upvotes   Int         @default(0)
  downvotes Int         @default(0)
  comments  Comment[]
  author    UserProfile @relation(fields: [authorId], references: [id])
  authorId  String
}

Query

const user = await prisma.user.create({
    data: {
        username,
        emailEncrypted: encrypted,
        emailIv: iv,
        password: hashedPassword,
        profile: {
            create: {}, // create a UserProfile that assumes the created user's UUID as a relation
        },
    },
    select: {
        id: true,
    },
});

As you can see, I have tried to use create: {} in order to assume the user's UUID, but it fails to create an actual UserProfile, just a User, which of course breaks the system.

2 Answers

I ran this as well. In order to include profile data after creating the user I did the following tweak.

const user = await prisma.user.create({
    data: {
        username: "username",
        emailEncrypted: "encrypted",
        emailIv: "iv",
        password: "hashedPassword",
        profile: {
            create: {},
        },
    },
    select: {
        id: true,
        createdAt: true,
        emailConfirmed: true,
        emailIv: true,
        emailEncrypted: true,
        isAdmin: true,
        isMod: true,
        password: true,
        profile: true,
        username: true,
    },
});

This outputs,

enter image description here

No issue it worked fine.

Still wondering what the issue you faced was.

Can you paste the error log ?.

This is the correct way of adding relations in Prisma. You use create to add a relation and the UUID will automatically be added to that record. You do not need to do anything else. I tried the following and works fine for me:

Entry added

Resulting record is created

Related