Prisma, MongoDB many to many relation create request

145 Views Asked by At

I am trying to make a create request for gallery that has many to many relation with gallery_category. I was not able to create it in such way that gallery_category would update it's galleries array after creating gallery with relation to that category.

Here is my prisma schema:

model Gallery {
  id                  String             @id @default(auto()) @map("_id") @db.ObjectId
  gallery_categories  Gallery_category[] @relation(fields: [gallery_categoryIDs], references: [id])
  gallery_categoryIDs String[]           @db.ObjectId
  dimensions          Dimension[]        @relation(fields: [dimensionIDs], references: [id])
  dimensionIDs        String[]           @db.ObjectId
  bucket              String
  full_path           String
  price               Float
  size                Float
  time_created        DateTime
  updated_at          DateTime
  url                 String
  name                String
  image               String
  orderIDs            String[]           @db.ObjectId
  orders              Order[]            @relation(fields: [orderIDs], references: [id])
}

model Gallery_category {
  id         String    @id @default(auto()) @map("_id") @db.ObjectId
  title      String    @unique
  galleryIDs String[]  @db.ObjectId
  galleries  Gallery[] @relation(fields: [galleryIDs], references: [id])
}

And here is my Gallery create request:

async create(createGalleryDto: CreateGalleryDto) {
        return await this.prismaService.gallery.create({
            data: {
                ...createGalleryDto,
                dimensions: {
                    connect: {id: createGalleryDto.dimensionIDs[0]}
                },
                gallery_categories: {
                    connect: {id: createGalleryDto.gallery_categoryIDs[0]}
                }
            }
        })
    }

My second problem is that I have an array of IDs as each gallery can have multiple but I don't know how to go through each of them and connect them. That's why I was so far only trying with first ID of array.

I tried it the way you can see in code I shared as well as creating separate functions to update relations that did not work at all.

1

There are 1 best solutions below

0
Jakub Vaňo On

I found a solution for my problem when I try to add just one Gallery with this code:

async create(createGalleryDto: CreateGalleryDto) {
        return await this.prismaService.gallery.create({
            data: {
                ...createGalleryDto,
                dimensions: {
                    connect: createGalleryDto.dimensionIDs.map((dimension) => ({id: dimension}))
                },
                gallery_categories: {
                    connect: createGalleryDto.gallery_categoryIDs.map((gallery_category) => ({id: gallery_category}))
                }
            }
        })
    }