Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma One-to-one relation issue

Tags:

prisma

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.

like image 981
Eduard Avatar asked Oct 20 '25 17:10

Eduard


1 Answers

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.

like image 88
Nurul Sundarani Avatar answered Oct 25 '25 03:10

Nurul Sundarani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!