Home > OS >  prisma One-To-Many relationship isn't working
prisma One-To-Many relationship isn't working

Time:11-12

I really know that the problem Is with me and Prisma's one-to-many relationship is working alright but just bear with me please.

1. This is the model's part where I have the problem:

model Product{
  Id Int @id @default(autoincrement())
  Uuid String @unique @default(uuid())
  Title String
  BrandName String?
  Thumbnails Thumbnail[] // one to many between thumbnail and Product
  Price Float
  DiscountRate Float?
  Category Category @relation(fields: [CategoryId], references: [Id]) // one to many between Category and Product
  CategoryId Int // The field containing the ID of the Category of this product
  Status Status
  Favorite Boolean @default(false)
  Stock Int @default(0)
  Item Item[] // one to many between Item and Product
}

model Cart{
  Id Int @id @default(autoincrement())
  Items Item[] // one to many between Item and Cart
}

model Item{
  Id Int @id @default(autoincrement())
  Product Product @relation(fields: [ProductId], references: [Id]) // one to many between Item and Product
  ProductId Int  
  Quantity Int
  Cart Cart? @relation(fields: [CartId],references: [Id]) // one to many between Cart and Item
  CartId Int?
}

2. API Code (NextJs)

// addItem.js 

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

export default async (req, res) => {
  
  let PrId = req.body.prodId;
  let Qte = req.body.Qte;
  let newItem = await prisma.item.create({
    data:{
      Quantity: Qte,
      Product:{
        connect:{
          Id: PrId,
        },
      }, 
      Cart:{
        connect:{
          Id: req.body.cartId
        }
      }
    },
  });

  return res.status(200).json(newItem);
};

3. Problem's explanation:

Now the thing is that I have multiple carts in the database, each cart contains Items as shown in the model. The real problem is with creating new items:

  • Adding the first item goes smoothly.
  • When I wanna add another item which is connected to the same Product I get an error as follows:
Unique constraint failed on the constraint: `Item_ProductId_key`
    at RequestHandler.handleRequestError (C:\Users\Bachar\Desktop\First_Freelance\node_modules\@prisma\client\runtime\index.js:30873:13)  
    at RequestHandler.request (C:\Users\Bachar\Desktop\First_Freelance\node_modules\@prisma\client\runtime\index.js:30856:12)
    at async PrismaClient._request (C:\Users\Bachar\Desktop\First_Freelance\node_modules\@prisma\client\runtime\index.js:31836:16)        
    at async __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/addItem.js:12:19)
    at async Object.apiResolver (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\api-utils\node.js:367:9)
    at async DevServer.runApi (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\next-server.js:474:9)
    at async Object.fn (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\next-server.js:736:37)
    at async Router.execute (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\router.js:252:36)
    at async DevServer.run (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\base-server.js:381:29)
    at async DevServer.run (C:\Users\Bachar\Desktop\First_Freelance\node_modules\next\dist\server\dev\next-dev-server.js:724:20) {        
  code: 'P2002',
  clientVersion: '4.5.0',
  meta: { target: 'Item_ProductId_key' },
  page: '/api/addItem'
}

CodePudding user response:

First of all thanks for anyone who viewed this. I had a migration before the one above where the ProductId inside the Cart model flagged as @unique, Which I removed in this last migration. The problem was that the database wasn't in sync with this last Prisma Schema even after using npx prisma migrate dev. I copied the schema file, removed the whole prisma folder, used the npx prisma init to generate a new folder then pasted the schema, migrated and voila!!

Anyways if anyone has an idea on how to do it without removing the schema file It would be a big help to tell me, cuz that would have been one hell of a day if the app was already in production.

  • Related