Joh*_*ika 1 typescript graphql prisma prisma-graphql prisma2
在我的 Prisma 模式中,帖子和类别之间存在多对多关系。我添加了@map选项以匹配 Postgres snake_case 命名约定:
model Post {
id Int @id @default(autoincrement())
title String
body String?
categories PostCategory[]
@@map("post")
}
model Category {
id Int @id @default(autoincrement())
name String
posts PostCategory[]
@@map("category")
}
model PostCategory {
categoryId Int @map("category_id")
postId Int @map("post_id")
category Category @relation(fields: [categoryId], references: [id])
post Post @relation(fields: [postId], references: [id])
@@id([categoryId, postId])
@@map("post_category")
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试同时创建一个包含多个类别的帖子。如果存在类别,我想connect将类别添加到帖子中。如果该类别不存在,我想创建它。创建部分运行良好,但连接部分有问题:
await prisma.post.create({
data: {
title: 'Hello',
categories: {
create: [{ category: { create: { name: 'News' } } }],
connect: {
categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId
},
},
},
});
Run Code Online (Sandbox Code Playgroud)
如何使用我拥有的架构将现有类别连接到新帖子?
你在这里需要的是connectOrCreate.
所以这样的事情应该有效:
await prisma.post.create({
data: {
title: 'Hello',
categories: {
create: [
{
category: {
create: {
name: 'category-1',
},
},
},
{ category: { connect: { id: 10 } } },
],
},
},
});
Run Code Online (Sandbox Code Playgroud)
您还可以在此处的文档中阅读有关此内容的更多信息
| 归档时间: |
|
| 查看次数: |
3525 次 |
| 最近记录: |