Home > Blockchain >  Many to many relations prisma
Many to many relations prisma

Time:09-21

I'm new to backend and stuff. I have two models: Product and City. City can have many products and product can have many cities, so I created another table ProductsOnCities:

model City {
  id            Int         @id @default(autoincrement())
  name          String
  pickupPoints  PickupPoint[]
  products      ProductsOnCities[]
}

model Product {
  id            Int         @id @default(autoincrement())
  title         String
  price         Int
  cities        ProductsOnCities[]
}

model ProductsOnCities {
  city          City        @relation(fields: [cityId], references: [id])
  cityId        Int
  product       Product     @relation(fields: [productId], references: [id])
  productId     Int

  @@id([cityId, productId])
}

How can I insert data now? For example, I want to create city with 4 products (which is already existing in my database), do I really need to create 4 objects there as it shown in prisma docs? Below is an example from the documentation.

const assignCategories = await prisma.post.create({
  data: {
    title: 'How to be Bob',
    categories: {
      create: [
        {
          assignedBy: 'Bob',
          assignedAt: new Date(),
          category: {
            connect: {
              id: 9,
            },
          },
        },
        {
          assignedBy: 'Bob',
          assignedAt: new Date(),
          category: {
            connect: {
              id: 22,
            },
          },
        },
      ],
    },
  },
})

That's what I did:

const assignCategories = await prisma.city.create({
    data: {
      name: 'Toronto',
      products: {
        create: [
          {
            product: {
              connect: {
                id: 1
              },
            },
          },
          {
            product: {
              connect: {
                id: 15
              },
            },
          },
          {
            product: {
              connect: {
                id: 11
              },
            },
          },
          {
            product: {
              connect: {
                id: 18
              },
            },
          },
        ],
      },
    },
  })

It's working good but is there any way to do it more succinctly? Do I really need to pass a new "big" object for each product i'm adding? I tried to pass the array of product id's to connect but it doesn't work.

CodePudding user response:

Yes you would need to pass it this way as you're using explicit many-to-many relations.

You can convert your schema to implicit many-to-many relations and that would make the create/connect syntax easier.

  • Related