在我的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")
}
我正在尝试创建一个同时具有多个类别的帖子。如果类别存在,我想要将类别与帖子
连接
。如果类别不存在,我想要创建它。创建部分运作良好,但连接部分存在问题: 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
},
},
},
});
我该如何使用现有的模式连接一个新帖子和一个分类?
post_category
表中存在{ categoryId: 1, postId: 1 }
桥接记录,则会用{ categoryId: 1, postId: new_id }
替换桥接记录。换句话说,它会将另一篇文章的类别重新分配给这篇新文章。我不希望在创建新文章时影响任何其他文章。如果该类别不存在,我想创建一个新类别,如果存在,则添加一个新的桥接记录。这里有一个使用隐式关系的create
和set
的好例子:(url to follow),但它不起作用,因为我正在使用显式关系。 - Johnny Oshikatags: { set: [{ id: 1 }, { id: 2 }], create: { name: 'typescript' } }
,这正是我想要做的,但是似乎无法与我的显式关系配合使用。 - Johnny OshikacategoryId_postId
链接到category
(对格式不好抱歉),所以这会引发异常:connectOrCreate: { create: { category: { create: { name: 'category-1' } }, }, where: { categoryId_postId: { category: { name: 'category-1' }, }, } }
- Johnny Oshikaawait prisma.post.create({ data: { title: 'title', categories: { create: { category: { connect: { id: 1 } } } }, }, })
这将把帖子连接到现有类别,并在联接表中创建关系。 - Ryan