Hi guys, I am making a webshop for a school assign...
# orm-help
m
Hi guys, I am making a webshop for a school assignment. However i Can't figure the following: I have a shopping cart model with several CartItems, each CartItem contains a product ID and a quantity. When adding something to the cart i want to check if the cart already contains a CartItem with the product. And if so incease the quantity. and if not make an item. I cant figure out how to do this. How can i refactur this code to make it work?
Copy code
const cart = await prisma.cart.update({
        where: {
            id: dbUser.cartId,
        },
        data: {
            Items: {
                create: {
                    product: {
                        connect: {
                            id: parseInt(body.productId),
                        },
                    },
                    quantity: parseInt(body.quantity) || 1,
                },
            },
            totalPrice: 12,
        },
    });

    res.json(cart);
});
Here is a part of my schema
Copy code
model User {
  id            Int     @id @default(autoincrement())
  username      String  @unique
  password_hash String
  role          Role    @default(USER)
  orders        Order[]
  cart          Cart    @relation(fields: [cartId], references: [id])
  cartId        Int
}

model Cart {
  id         Int         @id @default(autoincrement())
  Items      CartItem[]
  totalPrice Float       @default(0)
  User       User[]
}

model CartItem {
  id        Int     @id @default(autoincrement())
  Order     Order?  @relation(fields: [orderId], references: [id])
  orderId   Int?
  product   Product @relation(fields: [productId], references: [id])
  productId Int     @unique
  Cart      Cart?   @relation(fields: [cartId], references: [id])
  cartId    Int?
  quantity  Int     @default(1)
}
s
For readability’s sake, I would probably solve this by splitting out the query similar to this:
Copy code
const alreadyExists = await prisma.cartItem.count({
    where: { productId: body.productId },
});

if (alreadyExists) {
    // Run an update
} else {
    // Run a create
}
I am: 1. Checking if the product is already in the cart 2. Running an update to increment the quantity & total costs if it does) 3. Adding the data if it doesn’t
Hey 👋 Just checking in here to see if this worked out for you?