[英]How to create a relations in models with mutation method in GraphQL?
我正在使用 GraphQL 創建電子商務 api。 我的棱鏡架構是
model Product {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
name String
price Int
stocks Int
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
Orders Order[]
}
model Order{
id Int @id @default(autoincrement())
product Product @relation(fields: [productId], references: [id])
productId Int
user User @relation(fields: [userId], references: [id])
userId Int
@@unique([productId, userId])
}
為了在用戶訂購產品時創建關系,我的 graphql 架構和解析器 function 應該是什么?
您的架構實際上應該如下所示:
model Product {
id Int @id @default(autoincrement())
name String
price Int
stocks Int
orders Order[]
createdAt DateTime @default(now())
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
orders Order[]
}
model Order {
id Int @id @default(autoincrement())
product Product @relation(fields: [productId], references: [id])
productId Int
user User @relation(fields: [userId], references: [id])
userId Int
@@unique([productId, userId])
}
並且您的 GraphQL 突變應該包含作為變量傳遞的用戶 ID 和產品 ID,您的解析器將如下所示:
await prisma.user.update({
where: {
id: 1,
},
data: {
orders: {
create: {
product: {
connect: {
id: 123,
},
},
},
},
},
})
這將為用戶 ID 1創建一個新訂單,並將產品 ID 123添加到訂單中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.