我有最基本的显式多对多关系:
model Category {
id Int @id @default(autoincrement())
title String @db.VarChar(24)
posts PostCategory[]
}
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(24)
categories PostCategory[]
}
model PostCategory {
category Category @relation(fields: [categoryId], references: [id])
categoryId Int
post Post @relation(fields: [postId], references: [id])
postId Int
@@id([categoryId, postId])
@@unique([categoryId, postId])
}
我现在尝试完成的是创建一个有n个类别的新帖子。假设我们有一个包含n个类别标题的字符串数组
const myStringArray = ["Category1", "Category2", "Category3", ...];
我如何创建一个查询,将所有这些添加到我的新创建的帖子?如果我把它放在静态,这不是问题,但我怎么处理一个列表,我不知道的大小?
const assignCategories = await prisma.post.create({
data: {
title: 'First Post Title',
categories: {
create: [
{
category: {
create: {
name: myStringArray[0],
},
},
},
{
category: {
create: {
name: myStringArray[1],
},
},
},
],
},
},
})
您可以使用Array.map()
将每个字符串元素映射到所需形状的对象
const myStringArray = ['Category1', 'Category2', 'Category3'];
const assignCategories = await prisma.post.create({
data: {
title: 'First Post Title',
categories: {
create: myStringArray.map((title) => ({
category: { create: { title } },
})),
},
},
});
Array.map()
docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map