I have two model in prisma - one package model and second variation model. They are in one to many relation
model Package {
id Int @id @default(autoincrement())
name String
title String
vocavive_user vocavive_user[]
variations Variation[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Variation {
id Int @id @default(autoincrement())
expiration Int
bdt Int
discount_bdt Int @default(00)
usd Int @default(00)
discount_usd Int @default(00)
status Boolean @default(false)
packages Package? @relation(fields: [package_id], references: [id], onDelete: Cascade)
package_id Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
I can insert data variation when I insert package data and variation data at the same time.
exports.createPackage = catchAsync(async (req, res) => {
const {
name,
title,
expiration,
bdt,
discount_bdt,
usd,
discount_usd,
status,
} = req.body;
const newPackage = await prisma.package.create({
data: {
name: name,
title: title,
variations: {
create: {
expiration,
bdt,
discount_bdt,
usd,
discount_usd,
status,
},
},
},
include: {
variations: true,
},
});
console.log(newPackage);
res.status(200).json(newPackage);
});
But in my case I need to insert value only into variation table.. I tried this
exports.createVariation = catchAsync(async (req, res) => {
const newVariation = await prisma.variation.create({
data: {
expiration: req.body.expiration,
bdt: req.body.bdt,
package_id: req.body.package_id,
},
});
res.status(200).json(`variation Created Successfully: ${newVariation}`);
});
but it shows me
38 exports.createVariation = catchAsync(async (req, res) => { 39 const newVariation = await prisma.variation.create( Foreign key constraint failed on the field:
Variation_package_id_fkey (index)
at RequestHandler.handleRequestError (D:\Firoz\demo_authentication\node_modules@prisma\client\runtime\index.js:34869:13) at RequestHandler.handleAndLogRequestError (D:\Firoz\demo_authentication\node_modules@prisma\client\runtime\index.js:34841:12) at RequestHandler.request (D:\Firoz\demo_authentication\node_modules@prisma\client\runtime\index.js:34836:12) at async PrismaClient._request (D:\Firoz\demo_authentication\node_modules@prisma\client\runtime\index.js:35926:16) at async D:\Firoz\demo_authentication\controllers\packageController.js:39:24 Error: Invalidprisma.variation.create()
invocation in
How can I solve this problem?
The error message suggests that there doesn't exist a package with id that you are providing in package_id
field.
You can omit the package_id
field if it isn't needed or you would need to make sure that package with the value of package_id you are passing exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.