在 Prisma 的数据模型中,如果一个 discussion 有多个 posts,并且还需要持有 firstPost 和 lastPost 的字段,可以使用关系字段和计算字段来处理。\n\n首先,定义 `Discussion` 和 `Post` 的数据模型:\n\nprisma\nmodel Discussion {\n id Int @id @default(autoincrement())\n title String\n posts Post[]\n firstPost Post? @relation(name: \"FirstPost\", fields: [firstPostId], references: [id])\n lastPost Post? @relation(name: \"LastPost\", fields: [lastPostId], references: [id])\n firstPostId Int?\n lastPostId Int?\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n content String\n discussion Discussion @relation(fields: [discussionId], references: [id])\n discussionId Int\n}\n\n\n上述模型中,`Discussion` 拥有一个关系字段 `posts`,用于表示该讨论下的所有帖子。同时,还定义了两个可选的关系字段 `firstPost` 和 `lastPost`,分别指向第一篇帖子和最后一篇帖子。\n\n然后,需要创建一个迁移并应用它,以更新数据库模式:\n\nshell\nnpx prisma migrate dev --name add_first_last_post_fields\n\n\n接下来,可以在 Prisma Client 中使用这些关系字段来查询和操作数据。例如:\n\ntypescript\nconst discussion = await prisma.discussion.findUnique({\n where: { id: discussionId },\n include: {\n posts: true,\n firstPost: true,\n lastPost: true,\n },\n});\n\nconsole.log(discussion.posts); // 所有帖子\nconsole.log(discussion.firstPost); // 第一篇帖子\nconsole.log(discussion.lastPost); // 最后一篇帖子\n\n\n如果需要自动更新 `firstPost` 和 `lastPost` 字段,可以使用 Prisma 的计算字段功能。在数据模型中添加以下字段:\n\nprisma\nmodel Discussion {\n // ...\n firstPostCreatedAt DateTime? @updatedAt\n lastPostCreatedAt DateTime? @updatedAt\n}\n\n\n然后,创建另一个迁移并应用它,以更新数据库模式:\n\nshell\nnpx prisma migrate dev --name add_first_last_post_created_at_fields\n\n\n现在,每当讨论的帖子列表发生变化时,`firstPostCreatedAt` 和 `lastPostCreatedAt` 字段会自动更新为第一篇帖子的创建时间和最后一篇帖子的创建时间。\n\n请注意,上述方案是使用 Prisma 的关系字段和计算字段来实现的,具体的实现方式可能根据实际需求而有所不同。


原文地址: https://www.cveoy.top/t/topic/pHpF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录