将隐式多对多关系转换为显式多对多关系
问题
多对多关系是关系型数据库的重要方面,它允许一个表中的多条记录与另一个表中的多条记录相关联。Prisma 提供了两种方法来建模多对多关系:隐式和显式。
用户有时会遇到需要将模型之间隐式多对多关系转换为显式关系的情况。将隐式关系转换为显式关系可以让您更好地控制关系,并存储特定于关系的其他数据,例如时间戳或任何其他字段。本指南提供了关于如何进行这种转换的逐步演练。
解决方案
本指南将引导您完成在 Prisma 中将隐式多对多关系转换为显式关系的过程
考虑以下模型,它们通过 posts
和 author
字段具有隐式多对多关系
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
authors User[]
}
在上面的模型中,一个 User
可以有多个帖子,一个 Post
可以有多个作者。
要将隐式关系转换为显式关系,我们需要创建一个关系表。关系表将包含外键,引用多对多关系中涉及的两个表。在我们的示例中,我们将创建一个名为 UserPost
的新模型。我们更新后的 schema.prisma
文件将如下所示
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
userPosts UserPost[]
}
model Post {
id Int @id @default(autoincrement())
title String
authors User[]
userPosts UserPost[]
}
model UserPost {
id Int @id @default(autoincrement())
userId Int
postId Int
user User @relation(fields: [userId], references: [id])
post Post @relation(fields: [postId], references: [id])
createdAt DateTime @default(now())
@@unique([userId, postId])
}
如果您正在使用 Prisma Migrate,那么您可以调用此命令
npx prisma migrate dev --name "added explicit relation"
迁移将创建 UserPost
表,并创建 User
和 Post
模型与 UserPost
模型的一对多关系。
将现有数据从隐式关系表迁移到新创建的关系表
要将现有数据从隐式关系表迁移到新的显式关系表,您需要编写自定义迁移脚本。您可以使用 Prisma Client 与数据库交互,从隐式关系表中读取数据,并将其写入新的关系表。
考虑到上述 User
和 Post
模型,这是一个您可以用来迁移数据的示例脚本。
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
// A `main` function so that you can use async/await
async function main() {
try {
// Fetch all users with their related posts
const users = await prisma.user.findMany({
include: { posts: true },
});
// Iterate over users and their posts, then insert records into the UserPost table
for (const user of users) {
for (const post of user.posts) {
await prisma.userPost.create({
data: {
userId: user.id,
postId: post.id,
},
});
}
}
console.log("Data migration completed.");
} catch (e) {
console.error(e);
}
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
一旦数据迁移到关系表,您可以删除隐式关系列(User
模型中的 posts
和 Post
模型中的 author
),如下所示
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
userPosts UserPost[]
}
model Post {
id Int @id @default(autoincrement())
title String
authors User[]
userPosts UserPost[]
}
在 schema 文件中进行更改后,您可以调用此命令
npx prisma migrate dev --name "removed implicit relation"
运行上述命令将删除隐式表 _PostToUser
您现在已成功地在 Prisma 中将隐式多对多关系转换为显式关系。