asanas
asanas

Reputation: 4280

Prisma: Create or Connect Records in Explicit Many-to-Many Relations

In my Prisma Schema, I'm finding it difficult to undertand how to to create records in case of explicit many-to-many relations.

I have the following schema. Basically it represents Lists of Books. Users can Create Lists of Books.

A user can create a New list and then add books to this list along with their own notes. The Book Model is pure and contains standard book information.

The extra model is required because the user who is adding the book to the list can add his own notes about the book.

    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")
    }

The queries that I want to be able to do.

Upvotes: 0

Views: 3662

Answers (1)

Konrad
Konrad

Reputation: 287

It will be something like that:

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

However I see flaws in database schema. Model BooksInLists connects Books and List, so you don't need adder relation. In turn in Book model you shouldn't add curator relation because it's many to many relation. You have to use junction table usersBooks that connects User and Book tables.

Upvotes: 2

Related Questions