'How to create a cart model in prisma in relation with user and product models?
I have a product and user model in schema.prisma.
type Photo {
height Int
width Int
url String
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
password String
products Product[]
role Role
profileImg Photo
}
model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
price Int
stock Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
brand String
}
Now, I want to make a cart model which will have two fields one for the user and another for cartItems. Its type should be like
type cartItems = {product: Product, quantity: number}[]
Now how do I create the cart model for this. since I can't write like this
type CartItem {
product: Product
quantity: Int
}
model Cart {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String @db.ObjectId
user User @relation(fields: [userId], references: [id])
cartItems CartItem[]
}
because composite type can't have relations. One way I can do it, is by changing CartItem type to this
type cartItem {
productId String @db.ObjectId
quantity Int
}
But, in this case, for getting products in cart items, a separate request need to be made with the productId.
Is there any better solution?
Solution 1:[1]
You could use a groupby with callback and return the id based on sequence. As there is no overlap in the size of your ranges the best approach might be to just hardcode the if-else structure. A little prettier could be to make an array out of it e.g.
$ranges = [
[
'min' => 1
'max' => 4,
],
...
];
Solution 2:[2]
I'd say the cleaner way would be to change your table as to include a "min" and "max" column. This way, you'll be able to easily get the expected result with an SQL request (giving you the option to use it on your Models too)
If you do so, your request will look something like this and give you the expected result :
"SELECT * FROM sequence_table WHERE $sequence > sequence_table.min AND $sequence < sequence_table.max"
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 | |
| Solution 2 | Amrani Fares |
