Eduard
Eduard

Reputation: 45

Prisma One-to-one relation issue

I have just recently started using prisma and I ran into an issue with relations. I have a user model and an address model.

model User {
    id         Int      @id @unique @default(autoincrement())
    username   String
}

model Address {
    id         Int      @id @unique @default(autoincrement())
    street     String
}

I need to add 2 addresses to the user: invoicing address and delivery address. In the address I don't need a user reference.

I thought this would work without issues by adding this to the user model:

  invoiceAddress   Address? @relation(name: "iAddress", fields: [iAddressId], references: [id])
  deliveryAddress   Address? @relation(name: "dAddress", fields: [dAddressId], references: [id])
  iAddressId Int?
  dAddressId Int?

But when saving the schema two user fields are added to the address model... which I don't need and now I have issues because they reference the same user model so I have to also name them and add scalar field...

Am I missing something??? This should be a basic use case imo.

Upvotes: 4

Views: 5765

Answers (1)

Nurul Sundarani
Nurul Sundarani

Reputation: 7558

This is a requirement from Prisma's end that relation fields should exist on both sides of the model, you cannot define relation field on only one model.

The following schema model should solve the issue for you:

model User {
  id              Int      @id @unique @default(autoincrement())
  username        String
  invoiceAddress  Address? @relation(name: "iAddress", fields: [iAddressId], references: [id])
  deliveryAddress Address? @relation(name: "dAddress", fields: [dAddressId], references: [id])
  iAddressId      Int?
  dAddressId      Int?
}

model Address {
  id           Int    @id @unique @default(autoincrement())
  street       String
  UserInvoice  User[] @relation(name: "iAddress")
  UserDelivery User[] @relation(name: "dAddress")
}

Please note that relation fields do not exist on database so UserInvoice and UserDelivery columns would not exist on Address table. Similarly invoiceAddress and deliveryAddress columns would not exist on User table.

Upvotes: 3

Related Questions