**These are my models:**
model Category {
id Int @id @default(autoincrement())
name String @unique @db.VarChar(50)
product Product[]
@@map("categories")
}
model Product {
id Int @id @default(autoincrement())
name String @unique @db.VarChar(35)
barcode String @unique @db.VarChar(35)
sell Decimal @db.Decimal(12, 2)
shop Decimal @db.Decimal(12, 2)
quantity Int
expiresIn String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
categoryId Int
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade, onUpdate: Cascade)
sales SaleOrder[]
purchases PurchaseProduct[]
@@map("products")
}
model PurchaseProduct{
name String @db.VarChar(50)
sell Decimal @db.Decimal(12, 2)
shop Decimal @db.Decimal(12, 2)
quantity Int
expiresIn String
purchaseId Int
purchase Purchase @relation(fields: [purchaseId], references: [id], onDelete: Cascade, onUpdate: Cascade)
productId Int
product Product @relation(fields: [productId], references: [id], onDelete: Cascade, onUpdate: Cascade)
@@id([purchaseId, productId])
@@map("purchaseProducts")
}
model Purchase{
id Int @id @default(autoincrement())
supplierId Int
supplier Supplier @relation(fields: [supplierId], references: [id], onDelete: Cascade, onUpdate: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
purchases PurchaseProduct[]
@@map("purchases")
}
model Supplier {
id Int @id @default(autoincrement())
name String @unique @db.VarChar(35)
email String? @unique @db.VarChar(35)`your text`
contact String? @unique @db.VarChar(10)
products Purchase[]
@@map("suppliers")
}
**What I have tried:**
export async function create(formData: Purchase){
const purchase = await db.purchase.create({
data: {
name: formData.name,
sell: formData.sell,
shop: formData.shop,
quantity: formData.quantity,
supplier: {
connectOrCreate:{
where:{name: formData.supplierName},
create:{name: formData.supplierName, contact: formData.phone, email: formData.email}
}
},
product:{
connectOrCreate:{where:{name:formData.name},
create:{
name: FormData.name,
barcode: formData.barcode,
sell:formData.sell,
shop: formData.shop,
quantity: formData.quantity,
expiresIn: formData.expiresIn,
categoryId: formData.categoryId
}}
}}
})
return purchase;
}
I have tried using connect and connectOrCreate but it did not work, because for each insertion of purchase it may have many products, so my idea is to insert many products of each purchase.
For example, for each purchase there will have product 1, product 2, product 3 and etc. I want to pass array of data/json containg these products and then insert int the three tables at once.