Rafael Aguiar Gomes
Rafael Aguiar Gomes

Reputation: 101

Prisma 1:1 relation with no optional field on MySQL?

I was looking Prisma's documentation for 1:1 relation and i saw this piece of code:

  id      Int      @id @default(autoincrement())
  profile Profile?
}

model Profile {
  id     Int  @id @default(autoincrement())
  user   User @relation(fields: [userId], references: [id])
  userId Int  @unique // relation scalar field (used in the `@relation` attribute above)
}

and it says that a user can have 0 or 1 profiles. But what if I want ensure that a user must have a profile?

Upvotes: 0

Views: 1421

Answers (2)

naivary
naivary

Reputation: 46

The accepted answer should be declared false, because the "?" is mandatoy see this section.

Upvotes: 3

Raphael Etim
Raphael Etim

Reputation: 813

You can choose if the side of the relation with a relation scalar should be optional or mandatory. In the following example, profile and profileId are required. This means that you cannot create a User without connecting or making a Profile

model User {
  id        Int     @id @default(autoincrement())
  profile   Profile @relation(fields: [profileId], references: [id]) // references `id` of `Profile`
  profileId Int     @unique // relation scalar field (used in the `@relation` attribute above)
}

model Profile {
  id   Int   @id @default(autoincrement())
  user User
}

See this section of the docs for required and optional 1-1 relation.

Upvotes: 1

Related Questions