How to only foreign key in Prisma not the whole object

Viewed 630

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
3 Answers

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: {
           ...,
        }
    }
  },
})

The fields emp in the Client model and client in Employe model are relation fields so they won't exist in the database, they are just at the prisma level.

You only need to define the foreign key on one side of the relation - One to One relation Prisma reference

You could store clientId on the Employe model as well.

Related