Prisma:在显式多对多关系中创建或连接记录

问题描述

在我的 prisma Schema 中,我发现很难理解如何在显式多对多关系的情况下创建记录。

我有以下架构。基本上它代表书籍列表。用户可以创建图书列表。

用户可以创建一个新列表,然后将书籍和他们自己的笔记添加到该列表中。图书模型是纯粹的,包含标准图书信息。

需要额外的模型,因为将书添加到列表的用户可以添加他自己的关于该书的注释。

model List {
  id        Int     @default(autoincrement()) @id
  title     String
  slug      String?
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields: [authorId],references: [id])
  authorId  Int?
  books     BooksInLists[]
  createdAt DateTime @default(Now())
  updatedAt DateTime @updatedAt
}

model BooksInLists {
  list        List     @relation(fields: [listId],references: [id])
  listId      Int      // relation scalar field (used in the `@relation` attribute above)
  book    Book @relation(fields: [bookId],references: [id])
  bookId  Int      // relation scalar field (used in the `@relation` attribute above)
  @@id([listId,bookId])
  adder    User?   @relation(fields: [adderId],references: [id])
  adderId  Int?
  notes   String?
}

model Book {
  id     Int     @id @default(autoincrement())
  name   String
  lists  BooksInLists[]
  curator    User?   @relation(fields: [curatorId],references: [id])
  curatorId  Int?
  bookDescription  String?
}

model User {
  id            Int       @default(autoincrement()) @id
  name          String?
  email         String?   @unique
  lists         List[]
  books         Book[]
  booksinlists  BooksInLists[]

  @@map(name: "users")
}

我希望能够执行的查询

  • 更新列表时,我应该能够在列表中添加一本新书。这应该会创建新书,并且还允许我在 BooksInLists 模型中添加新记录以及“注释”字段。

  • 更新列表时,我应该能够将现有书籍添加/连接到列表。这将允许我在 BooksInLists 模型中添加一条新记录以及“注释”字段。

解决方法

它会是这样的:

    prisma.booksInLists.create({
        data: {
          list: {
            connect: {
              id: 99
            },},book: {
            create: {
              name: 'Young Lions'
            }
          }
        }
      })

但是我发现数据库架构存在缺陷。模型 BooksInLists 连接 BooksList,因此您不需要 adder 关系。反过来,在 Book 模型中,您不应该添加 curator 关系,因为它是多对多关系。您必须使用连接表 usersBooks 来连接 UserBook 表。