'Nested writes in Prisma orm
My schema looks like this:
model Transaction {
id BigInt @id @default(autoincrement())
description String? @db.VarChar(256)
category Category? @relation(fields: [categoryId], references: [id])
createdById Int @map("fk_created_by")
createdBy UserAccount @relation("category_fk_created_byTouser_account", fields: [createdById], references: [id]
}
model Category {
id Int @id @default(autoincrement())
name String @db.VarChar(40)
categoryFilters CategoryFilter[]
}
model CategoryFilter {
id BigInt @id @default(autoincrement())
words String @db.VarChar(255)
categoryId Int? @map("fk_category_id")
}
My question is why this works:
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdBy: {
connect: {
id: 1
}
},
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
And this not?
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdById: 1,
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
The only difference between those two examples is in createdBy command. And i can create Transaction without nested objects with createdById argument. Any one know why this works this way? Or there is something i am missing?
The error given is:
Unknown arg createdById in data.createdById for type TransactionCreateInput
Solution 1:[1]
In the second example, you are directly writing a foreign key (createdById) which is considered unsafe, what if there is no UserAccount corresponding to createdById.
While using connect in the first example it would throw an error if Prisma cannot find an UserAccount corresponding to id 1.
First example is the preferred approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nurul Sundarani |
