Home > OS >  How to only foreign key in Prisma not the whole object
How to only foreign key in Prisma not the whole object

Time:04-22

I've just started learning nestjs and I'm using Prisma as my ORM, I've created two models (Employees, Clients), these models will contain foreign keys , the client will have the employee id and vice versa (a one-to-one relation), but as you will see in the models the employee will contain the whole Client "object", but what I want also is his client's id as an independent column :

this is the models:

model Employe {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updated   DateTime @updatedAt

  email String @unique
  hash  String

  nom    String
  prenom String

 // I want the client ID here too
  
  client Client? 

  @@map("employes")
}

model Client {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updated   DateTime @updatedAt

  email String @unique
  hash  String

  nom    String
  prenom String

  EmpId Int?     @unique
  emp   Employe? @relation(fields: [EmpId], references: [id], onDelete: Cascade, onUpdate: Cascade)

  @@map("clients")
}

So is there any way ?

  • Framework: NestJS
  • ORM: Prisma
  • DB : Postgresql
  • Platform: Docker

CodePudding user response:

In this link there is an example that can help you:

https://www.prisma.io/docs/guides/general-guides/database-workflows/foreign-keys/postgresql

CodePudding user response:

I more or less understand what you mean. I don't understand why you don't set relation, but you can use this structure when creating a client or employe.

to create the employe

await prisma.employe.create({
  data: {
    email: 'blabla',
    hash: 'balbla',
    nom: 'blabla',
    prenom: 'balbla',
    clientId: 123,
    include: {
        client: {
           ...,
        }
    }
  },
})

to create the client

await prisma.client.create({
  data: {
    email: 'blabla',
    hash: 'balbla',
    nom: 'blabla',
    prenom: 'balbla',
    employeId: 123,
    include: {
        employe: {
           ...,
        }
    }
  },
})
  • Related